C Sharp StreamWriter

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# StreamWriter

C# StreamWriter class is used to write characters to a stream in specific encoding. It inherits TextWriter class. It provides overloaded write() and writeln() methods to write data into file.

C# StreamWriter example

Let's see a simple example of StreamWriter class which writes a single line of data into the file.

 
  1. using System;  
  2. using System.IO;  
  3. public class StreamWriterExample  
  4. {  
  5.     public static void Main(string[] args)  
  6.     {  
  7.         FileStream f = new FileStream("e:output.txt", FileMode.Create);  
  8.         StreamWriter s = new StreamWriter(f);  
  9.   
  10.         s.WriteLine("hello c#");  
  11.         s.Close();  
  12.         f.Close();  
  13.      Console.WriteLine("File created successfully...");  
  14.     }  
  15. }  

Output:

File created successfully...

Now open the file, you will see the text "hello c#" in output.txt file.

output.txt:

hello c#