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 .
Software Professional, India

IT professional with 15+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

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