Hviidnet.com
22Oct/080

Reading and writeing to files in C#

// file IO using class StreamWriter
//
// SnippetCompiler.exe was used to write, compile (uses .NET V2 csc.exe)

using System;
using System.IO; // TextWriter, StreamWriter

public class MyClass
{
public static void Main()
{
string text;

text = "Why Did the Chicken Cross the Road?\n";
text += "ARISTOTLE: It is the nature of chickens to cross roads.\n";
text += "RONALD REAGAN: I forget.\n";
text += "CAPTAIN JAMES T. KIRK: To boldly go where no chicken has gone before.\n";
text += "ERNEST HEMINGWAY: To die. In the rain.\n";
text += "COLONEL SANDERS: I missed one?";

// create a writer and open the file
TextWriter tw = new StreamWriter("date.txt");

// write a line of text (present date/time) to the file
tw.WriteLine(DateTime.Now);

// write the rest of the text lines
tw.Write(text);

// close the stream
tw.Close();

// read the text file back ...
// create reader & open file
TextReader tr = new StreamReader("date.txt");

// read first line of text (here date/time)
Console.WriteLine(tr.ReadLine());

// read the text, next 2 lines
Console.WriteLine(tr.ReadLine());
Console.WriteLine(tr.ReadLine());

// read the rest of the text lines
Console.WriteLine(tr.ReadToEnd());

// close the stream
tr.Close();

// wait to look at console display
Console.Write("\nPress Enter to exit ...");
Console.Read();

}
}

Tagged as: , No Comments