StreamWriter Class in C# with Example

StreamWriter Class in C# with Example
StreamWriter Class in C# with Example

StreamWriter class is used for writing directly to the text files.  Like StreamReader class, it also resides in System.IO namespace and you must also include the same on top of your code file.  While creating an instance of StreamWriter class, you can directly pass the path of the text file to the constructor.  If the file does not exist, StreamWriter will create a file for you in that location.  StreamWriter class contains methods like Write(), WriteLine() etc.

Write() method is used for writing text in the same line.  WriteLine() method is used for writing text in every new line.  There is a method called Close() in the StreamWriter class. You must invoke that method after you finished writing your text file to release any system resources associated with the writer.

using System;
using System.IO;

namespace Hello
{   

    class Program
    {
        static void Main(string[] args)
        {
            //Creating instance of StreamWriter.
            StreamWriter _sw = new StreamWriter(@"C:\Users\Admin\Desktop\mytext.txt");
            _sw.WriteLine("John Jackson");

            _sw.Close();
           
        }
            
    }
}