Suppose you want to read a text file in C#, TestFile.txt, into your program. The simplest way to do so is by using Streams in the System.IO namespace.
However that's the big picture. There are several ways to actually load a text file into C#, we are going to explore two different ways to do it.
The first and simplest way to read a file is to use the StreamReader class in C#:
StreamReader textFile = new StreamReader(path); string fileContents = textFile.ReadToEnd(); textFile.Close();
However here we reach a problem: the entire contents of the text file is being read all at once. If the text file is small or we do not need to do anything with individual lines then that's fine.
However, say we want to append a line number to each line we read. In order to do so, we have to use the StringReader class to read through the entire string and count the number of lines. Then we can go back and go through the lines individually.
There is a much better way to read a text file in C#. This method not only allows you to read a text file by lines, it allows you to do so the first time it's being read, giving us the ability to track the progress.
First we load the file's content in the form of bytes into a byte[] array. For this example I read all the content at once, if you want to read individual bytes at a time, use the function ReadByte.
FileStream textFile = new FileStream(path, FileMode.Open); byte[] buffer = new byte[textFile.Length]; textFile.Read(buffer, 0, buffer.Length);
Then, once we have all the bytes stored in an array, we need to go through the bytes and find the end of the lines. To do so, we are looking two bytes in a row: 13 and 10. In a Windows OS system, the bytes 13-10 mark the end of a line (vbCrLf in Visual Basic).
int lineCount = 0; for (int i = 0; i < buffer.Length; i++) { if (buffer[i] == 13) if (i + 1 < buffer.Length && buffer[i + 1] == 10) lineCount++; }
With the line count, we can go back and use the StringReader class to read each line of the text file.
The example C# project includes functions that illustrate both of these methods to load a text file. You might also want to take a look at how to write binary files in C#.