How to Read a File in C#

Csharp was probably the first compiled language I really loved. When the first version of .net came out I wrote a small CMS using C# and the new runtime. (A big step up from old school asp)

Reading a file - here as a stream - is easy. Setup a streamreader and call ReadLine on it, until it returns null.

string line;
int linenum;
System.IO.StreamReader file = new System.IO.StreamReader("test.csharp");
while((line = file.ReadLine()) != null) {
  linenum++;
  Console.WriteLine (linenum + " : " + line);
}

We prefix each line with a linenumber.

Related Posts