Wednesday, May 30, 2007

Reading and Writing Text Files - C#

// File IO using class StreamWriter

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

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

text = "A quick brown fox\n";
text += "jumps over a \n";
text += "little lazzy dog.\n";

// create a writer and open the file
TextWriter tw = new StreamWriter("typing.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("typing.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();

}
}

1 comment:

Anonymous said...

good article....good work

knowledge sharing is good habbit!!!

great going