In c#, StreamWriter is a class of System.IO namespace and it is useful to write characters to the stream with a particular encoding. The StreamWriter class has been derived from TextWriter to provide the implementation of members for writing to a stream and by default, it will use UTF8Encoding unless we specify other encodings.
Now, we will see how to use the StreamWriter class in c# to write a text to the file with examples.
Following is the example of writing a text to file using the StreamWriter object in c#.
static void Main(string args)
string fpath = @"D:\Test.txt";
// Check file if exists
// Create the file
FileStream fs = new FileStream(fpath, FileMode.Create);
using (StreamWriter sw = new StreamWriter(fs))
sw.WriteLine("\r\nWelcome to Tutlane");
When we execute the above example, it will create a new “Test.txt” file in D drive with required text like as shown following.
This is how we can create, delete and add text to files using File, FileStream & StreamWriter objects in c#.