Open In App

File.ReadLines(String) Method in C# with Examples

File.ReadLines(String) is an inbuilt File class method that is used to read the lines of a file.

Syntax:



public static System.Collections.Generic.IEnumerable ReadLines (string path);

Parameter: This function accepts a parameter which is illustrated below:

  • path: This is the specified file for reading.

Exceptions:



Return Value: Returns all the lines of the specified file.

Below are the programs to illustrate the File.ReadLines(String) method.

Program 1: Initially, a file file.txt is created with some contents shown below-




// C# program to illustrate the usage
// of File.ReadLines(String) method
  
// Using System and System.IO namespaces
using System;
using System.IO;
  
public class GFG {
    public static void Main(String[] argv)
    {
        // Calling the ReadLines(String) function
        foreach(string line in File.ReadLines(@"file.txt"))
        {
            // Printing the file contents
            Console.WriteLine(line);
        }
    }
}

Output:

GFG
gfg
Geeks
GeeksforGeeks
geeksforgeeks

Program 2: Initially, a file file.txt is created with some contents shown below-

Below code filter some contents from the file and prints them back.




// C# program to illustrate the usage
// of File.ReadLines(String) method
  
// Using System and System.IO namespaces
using System;
using System.IO;
  
public class GFG {
    public static void Main(String[] argv)
    {
        // Calling the ReadLines(String) function
        foreach(string line in File.ReadLines(@"file.txt"))
        {
            // Filtering the file contents and printing
            if (line.Contains("GFG")) {
                Console.WriteLine(line);
            }
        }
    }
}

Output:

GFG

Article Tags :
C#