MOCKSTACKS
EN
Questions And Answers

More Tutorials




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 using ReadLines() 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 using StreamReader() 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);
    }
}

Conclusion

In this page (written and validated by ) you learned about How to read a specific line in a text file in C#? . What's Next? If you are interested in completing C# tutorial, we encourage you simply to start here: C# Tutorial.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.