how to read all lines in a file in c# code example
Example 1: c# read file line by line
int counter = 0;
string line;
System.IO.StreamReader file =
new System.IO.StreamReader(@"c:\test.txt");
while((line = file.ReadLine()) != null)
{
System.Console.WriteLine(line);
counter++;
}
file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
System.Console.ReadLine();
Example 2: c# read all lines from filestream
public IEnumerable<string> ReadLines(Func<Stream> streamProvider,
Encoding encoding)
{
using (var stream = streamProvider())
using (var reader = new StreamReader(stream, encoding))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
Example 3: how to read particular line of file in c#
string GetLine(string fileName, int line)
{
using (var sr = new StreamReader(fileName)) {
for (int i = 1; i < line; i++)
sr.ReadLine();
return sr.ReadLine();
}
}