Mega Code Archive

 
Categories / C# Book / 07 Stream
 

0569 StreamReader and StreamWriter

In the following example, a StreamWriter writes two lines of text to a file, and then a StreamReader reads the file back: using System; using System.IO; using System.Linq; class Program { static void Main() { using (FileStream fs = File.Create("test.txt")) using (TextWriter writer = new StreamWriter(fs)) { writer.WriteLine("Line1"); writer.WriteLine("Line2"); } using (FileStream fs = File.OpenRead("test.txt")) using (TextReader reader = new StreamReader(fs)) { Console.WriteLine(reader.ReadLine()); // Line1 Console.WriteLine(reader.ReadLine()); // Line2 } } }