how to read lines in a text file 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: text file read all lines c#
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
if (!File.Exists(path))
{
string[] createText = { "Hello", "And", "Welcome" };
File.WriteAllLines(path, createText);
}
string appendText = "This is extra text" + Environment.NewLine;
File.AppendAllText(path, appendText);
string[] readText = File.ReadAllLines(path);
foreach (string s in readText)
{
Console.WriteLine(s);
}
}
}