Monday, May 24, 2021

C# StreamWriter Class

StreamWriter class belongs to System.IO namespace and is used to write text in a file. The StreamWriter class derives from TextWriter and provides implementations of the members for writing to a stream. StreamWriter is designed for character output in a particular encoding, whereas classes derived from Stream are designed for byte input and output. 
The StreamWriter class has non-static methods and properties and so, an instance of StreamWriter class should be created to access its members. The Write and WriteLine methods of StreamWriter class have many overloaded versions which are described at https://docs.microsoft.com/en-us/dotnet/api/system.io.streamwriter?view=net-5.0

The following example demonstrates it. In the example, using block is used. The using statement automatically calls Dispose on the object when the code that is using it has completed.

using System;
using System.IO;
namespace ConsoleStreamWriter
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"F:\TestW.txt";//verbatim literal
            using(FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (StreamWriter writer = new StreamWriter(fs))
                {
                    writer.WriteLine("I am learning C# StreamWriter class.");
                    writer.Write("More lines can be written...");
                    Console.WriteLine("Encoding used:{0}",writer.Encoding);
                    Console.WriteLine("Text written in new file...");
                }
            }
            Console.ReadKey();
        }
    }
}

No comments:

Post a Comment

Hot Topics