C#: Read a file using while statement

Following the previous post, we make use of the while statement to read a file and output the content to the console.

At the same time, we will not display the blank lines in the file to the console.

using System;
using System.IO;

namespace ReadFile
    class Program
        static void Main()
            string line;

            // Read the file and display non-blank line by line.
            StreamReader file = new StreamReader("c:\\test.txt");
            while ((line = file.ReadLine()) != null)
                if (!string.IsNullOrEmpty(line))  //remove blank lines


            // Suspend the screen.

The example makes use of StreamReader class to put the file text.txt into the file instance.

The ReadLine is a method of StreamReader class.  

In line 14, each text line is stored into the string line and displayed on the screen.

In line 16, the if statement checks for blank line.


If the line is not blank, it will output the line to the console. Else it will read till the EOF is reached.

In the file name c:\test.text.  There is a special character \.  So we need to escape it using \ and that is why we have c:\\test.txt in line 13.

In C#, there is a special technique that we can use which is to escape the entire double quote.  So we can write the line as:

StreamReader file = new StreamReader(@"c:\test.txt");



Series Navigation<< C#: The while statement
C#: Read a file and output to a second file >>