Reading a text file using streamreader.
using (StreamReader sr = new StreamReader(FileName, Encoding.Default))
{
string line = sr.ReadLine();
}
<
string text = sr.ReadToEnd();
string[] lines = text.Split('\r');
foreach(string s in lines)
{
// Consume
}
You either have to parse the stream byte-by-byte yourself and handle the split, or you need to use the default ReadLine behavior which splits on /r, /n, or /r/n.
If you want to parse the stream byte-by-byte, I'd use something like the following extension method:
public static string ReadToChar(this StreamReader sr, char splitCharacter)
{
char nextChar;
StringBuilder line = new StringBuilder();
while (sr.Peek() > 0)
{
nextChar = (char)sr.Read();
if (nextChar == splitCharacter) return line.ToString();
line.Append(nextChar);
}
return line.Length == 0 ? null : line.ToString();
}
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);
}
}