Open a text file and read line by line in C#

Open a text file and read line by line in C#

There are several ways to open a text file and read line by line in c# programming language. The most common method is to use StreamReader to read a file line by line.

Reading From File Line by Line with StreamReader in C#

using (StreamReader sr = File.OpenText("path"))
{
    string s = "";
    while ((s = sr.ReadLine()) != null)
    {
        Console.WriteLine(s);
    }
}

It is also possible to use TextReader to read a file line by line in C#.

TextReader tr = new StreamReader("path");
Console.WriteLine(tr.ReadLine());
tr.Close();

Reading a text file into String[] in C#

Another method for reading a text file line by line is to use File.ReadAllLines method. If your file is small enough or if you want to access these lines multiple times, then you might load all the lines into memory and re-use them as given below:

string[] lines = File.ReadAllLines("path");
foreach (string line in lines)
{
    if (line.Length > 80)
    {
        Console.WriteLine(line);
    }
}


added 5 years 11 months ago

- How to POST and GET url with parameters in C#?
- Open a text file and read line by line in C#
- Convert.ToInt32() vs Int32.Parse() in C#
- How to C# Linq Group By by paramater/field names
- Simple Injector
- How to check memory consumption in c#
- How can I implement C/C++ "union" in C#?
- How to Open and Read From Excel File in C#
- Weak References
- Lazy Initialization
- Enable Nuget Package Restore
- OnixS FIX Engine
- Rapid Addition FIX API
- How to change DateTime format in C#
- How to change number decimal seperator in C#?
2
1