SoFunction
Updated on 2025-03-05

Several effective ways to read text files line by line in C#

In C#, there are several ways to effectively read text files line by line.

Read text files line by line using the () method in C#

The () method is the best way to efficiently read text files line by line. This method returns an enumerable type Enumerable for large text files, which is why we created an Enumerable string object to store text files.

The correct syntax for using this method is as follows:

(FileName);

Sample code:

using System;
using ;
using ;
 
public class ReadFile
{
    public static void Main()
    {
      string FileToRead = @"D:\New folder\";
      // Creating enumerable object  
      IEnumerable<string> line = (FileToRead);
      ((, line));   
    }
}

Output:

// All the text, the file contains will display here.

If there is a problem when opening the file, the () method will throw an IOException; if the requested file does not exist, a FileNotFoundException is thrown.

Read text files line by line using the() method in C#

The () method can also be used to read files line by line. It does not return Enumerable. It returns an array of strings containing all lines of the text file.

The correct syntax for using this method is as follows:

(FileName);

Sample code:

using System;
using ;
 
public class ReadFile
{
    public static void Main()
    {
      string FileToRead = @"D:\New folder\";
      // Creating string array  
      string[] lines = (FileToRead);
      ((, lines));   
    }
}

Output:

// All the text, the file contains will display here.

This method also throws an exception, just like the () method. Then use the try-catch block to handle these exceptions.

Read text files line by line using the () method in C#

The StreamReader class in C# provides the () method. This method reads the text file line by line to the end.

The correct syntax of the () method is as follows:

//We have to create Streader Object to use this method
StreamReader ObjectName = new StreamReader(FileName);
();

Sample code:

using System;
using ;
 
public class ReadFile
{
    public static void Main()
    {
      string FileToRead = @"D:\New folder\";
      using (StreamReader ReaderObject = new StreamReader(FileToRead))
      {
          string Line;
          // ReaderObject reads a single line, stores it in Line string variable and then displays it on console
          while((Line = ()) != null)
          {
              (Line);
          }
      }
        
    }
}

Output:

// All the text, the file contains will display here.

This is the end of this article about several effective methods for reading text files in C# line by line. For more related contents of C# reading text files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!