Mega Code Archive

 
Categories / C# Book / 07 Stream
 

0571 Read and Write various types

You can read and write other types such as integers, but because TextWriter invokes ToString on your type, you must parse a string when reading it back: using System; using System.IO; using System.Linq; class Program { static void Main() { using (TextWriter w = File.CreateText("data.txt")) { w.WriteLine(123); // Writes "123" w.WriteLine (true); // Writes the word "true" } using (TextReader r = File.OpenText("data.txt")) { int myInt = int.Parse(r.ReadLine()); // myInt == 123 bool yes = bool.Parse (r.ReadLine()); // yes == true } } }