how to read all lines in a text file in c# code example
Example 1: c sharp how to read a text file
string text = System.IO.File.ReadAllText(@"C:\filepath\file.txt");
string[] lines = System.IO.File.ReadAllLines(@"C:\filepath\file.txt");
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: 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);
}
}
}