C# StreamWriter
To write characters to a stream in a specific encoding, the C# StreamWriter class is used which inherits the TextWriter class. To write data into a file, the overloaded write() and writeln() methods are facilitated by the C# StreamWriter class.
Example:
using System; using System.IO; public class Example { public static void Main(string[] args) { FileStream fs = new FileStream("d:\\file.txt", FileMode.Create); StreamWriter sw = new StreamWriter(fs); sw.WriteLine("Hello World"); sw.Close(); fs.Close(); Console.WriteLine("Today is a Great day!!"); } } |
Console Output:
D:\\file.txt:
Explanation:
In the above example, we are using the StreamWriter class to write a single line of data into a file. Open the file and verify the text.