Reading a text file using streamreader.
using (StreamReader sr = new StreamReader(FileName, Encoding.Default))
{
string line = sr.ReadLine();
}
<
I needed a solution that reads until "\r\n", and does not stop at "\n". jp1980's solution worked, but was extremely slow on a large file. So, I converted Mike Sackton's solution to read until a specified string is found.
public static string ReadLine(this StreamReader sr, string lineDelimiter)
{
StringBuilder line = new StringBuilder();
var matchIndex = 0;
while (sr.Peek() > 0)
{
var nextChar = (char)sr.Read();
line.Append(nextChar);
if (nextChar == lineDelimiter[matchIndex])
{
if (matchIndex == lineDelimiter.Length - 1)
{
return line.ToString().Substring(0, line.Length - lineDelimiter.Length);
}
matchIndex++;
}
else
{
matchIndex = 0;
//did we mistake one of the characters as the delimiter? If so let's restart our search with this character...
if (nextChar == lineDelimiter[matchIndex])
{
if (matchIndex == lineDelimiter.Length - 1)
{
return line.ToString().Substring(0, line.Length - lineDelimiter.Length);
}
matchIndex++;
}
}
}
return line.Length == 0
? null
: line.ToString();
}
And it is called like this...
using (StreamReader reader = new StreamReader(file))
{
string line;
while((line = reader.ReadLine("\r\n")) != null)
{
Console.WriteLine(line);
}
}