How to read a specific line in a text file in C#?
There are multiple ways to read specific line from file in C# depending on your .NET version:1) Using ReadLines() Method
In below example we will be usingReadLines()
method followed by Skip()
function to skipe X number of lines finally followed by Take()
to specify the number of line to return after skipped lines.using System;
using System.IO;
public class Example
{
public static void Main()
{
string FileName = @"C:\FILE_NAME_HERE";
string lineContent= File.ReadLines(FileName).Skip(14).Take(1).First();
Console.WriteLine("Line Content: " + lineContent);
}
}
2) Using StreamReader() Class
In below example we will be usingStreamReader()
class which has a method called ReadLine()
, we can read lines while looping until we reach the line number we want.using System;
using System.IO;
public class Example
{
public static void Main()
{
int getLine = 15;
string FileName = @"C:\FILE_NAME_HERE";
string lineContent = "";
using (var sr = new StreamReader(FileName)) {
for (int i = 1; i < getLine; i++)
sr.ReadLine();
lineContent = sr.ReadLine();
}
Console.WriteLine("Line Content: " + lineContent);
}
}