Snippet - Read StreamReader Contents In Chunks 08-20-2012, 12:57 AM
#1
Here's a cool snippet I came up with to read using a StreamReader in chunks based on an input of how many lines you want to read at a time until the end of the Stream for the file.
Good example usage for where the null coalescing operator in C# comes in nicely as well :ok:
I used the fully fleged StringBuilder just in case we're dealing with a fair bit of lines based on the lnBufferCount for determining the buffer size for the string we're dealing with through the loop.
Enjoy
Good example usage for where the null coalescing operator in C# comes in nicely as well :ok:
I used the fully fleged StringBuilder just in case we're dealing with a fair bit of lines based on the lnBufferCount for determining the buffer size for the string we're dealing with through the loop.
Code:
private void MainMethod()
{
using (StreamReader sr = new StreamReader(@"F:\file.txt"))
{
string lnBuffer = string.Empty;
int lnBufferCount = 5;
//If based on user input:
if (lnBufferCount < 1) throw new ArgumentException("lnBufferCount cannot be less than 1.");
while (LinesAvailable(ref lnBuffer, ReadLines(lnBufferCount, sr)))
{
MessageBox.Show(lnBuffer);
}
}
}
private bool LinesAvailable(ref string lnBuffer, string readLine)
{
lnBuffer = readLine;
return !(lnBuffer.StartsWith("\0"));
}
private string ReadLines(int numLines, StreamReader reader)
{
StringBuilder sb = new StringBuilder();
Array.ForEach(Enumerable.Range(1, numLines).ToArray(), i => sb.AppendLine(reader.ReadLine() ?? "\0"));
return sb.ToString();
}
Enjoy
![Smile Smile](https://sinister.ly/images/smilies/set/smile.png)
ArkPhaze
"Object oriented way to get rich? Inheritance"
Getting Started: C/C++ | Common Mistakes
[ Assembly / C++ / .NET / Haskell / J Programmer ]
"Object oriented way to get rich? Inheritance"
Getting Started: C/C++ | Common Mistakes
[ Assembly / C++ / .NET / Haskell / J Programmer ]