c sharp read text file line by line code example
Example 1: 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);
}
}
}
Example 2: 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();
}
}