Sunday, August 30, 2009

Reading and writing Files and Streams

To read a text file, create an instance of TextReader or StreamReader. Then, call one of the class's methods to read as much or as little of the file as you want. For example, the following sample code displays a text file to the console:

// C#
TextReader tr = File.OpenText(@"C:\windows\win.ini");
Console.Write(tr.ReadToEnd());
tr.Close();

The previous example uses the TextReader class, but it works equally well with the StreamReader class (which counterintuitively derives from TextReader). When using TextReader, you tipically create an instance using the static File.OpenText method (as demonstrated in the previous example). When using StreamReader, you can use File.OpenText or the StreamReader constructor. The following example displays the same text file using an instance of StreamReader and a while loop:

// C#
StreamReader sr = new StreamReader(@"c:\windowswin.ini");
string input;
while((input = sr.ReadLine()) != null)
Console.WriteLine(input);
sr.Close();

To write a text file, create an instance of TextWriter or StreamWriter. After creating an instance of the class, writing to the file is no more complex than writing to the console. See the following code example:

//C#
TextWriter tw = File.CreateText("output.txt");
tw.WriteLine("Hello world!");
tw.Close();

If you want to be sure that data is written to the disk without closing the file, call the Flush method.

No comments:

Post a Comment