C# Read File
Open and read a file into streams:
1
2
3
4
5
6
7
8
9
using System.IO;
StreamReader sr = new StreamReader("test.txt");
string strLine = sr.ReadLine();
while (!sr.EndOfStream)
{
...
strLine = sr.ReadLine();
}
sr.Close();
If the file is relatively small, it can be read as one string at one time.
1
2
using System.IO.File;
string str = File.ReadAllText("Text.txt");
To read a file line by line.
1
2
3
4
5
6
using System.IO.File;
string[] arrlines = File.ReadAllLines("Text.txt");
foreach (string thisline in arrlines)
{
...
}