TechieClues TechieClues
Updated date Aug 19, 2022
This blog will teach us how to write a file using StreamWriter in C#.

Write a file using StreamWriter in C#:

The StreamWriter is used to write the characters to a stream. It is available under the namespace System.IO.

The FileInfo provides properties and instance methods for creating, copying, deleting, moving, and opening files, and helps create FileStream objects.

// Create fileInfo object and specify path            
FileInfo fileInfo = new FileInfo(@"E:\Test_File.txt");

The FileStream provides a stream for a file and is used for reading and writing operations.

// Open the file for Reading and Writing
FileStream fileStream = fileInfo.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);

Code Snippet:

The below example is used to create the file and append or add the new text to the file.

using System.IO;

namespace StreamWriterSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create fileInfo object and specify path            
            FileInfo fileInfo = new FileInfo(@"E:\Test_File.txt");

            // Open the file for Read and Write
            FileStream fileStream = fileInfo.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);

            // Write string to the FileSream object
            StreamWriter streamWriter = new StreamWriter(fileStream);
            streamWriter.WriteLine("Sample text inserted to the file");
            streamWriter.Close();
        }
    }
}

You can also visit the below blog to create and delete a file using StreamWriter & StreamReader in C#.

Create and Delete a File In C#

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!