patterncsharpMinor
Are 2 streams really needed?
Viewed 0 times
areneededreallystreams
Problem
I have a simple text file setup as a Resource through my application's Properties as a byte[]. In order to access a "Stream.ReadLine" function, I believe I need to make it into a StreamReader. Is there a way to get the following result using only 1 Stream, or else, any tricks to make it better?
List list = new List();
using (Stream s = new MemoryStream(myFile))
{
using (StreamReader sr = new StreamReader(s))
{
while (!sr.EndOfStream)
{
list.Add(sr.ReadLine());
}
}
}Solution
Not without having to reinvent a lot of other things and make it more complex, no. This solution looks to be the best to me. You even use
...
using correctly, which is one of my frequent nitpicks. However, if you want to simplify that bit of code, you might be able to help it with an extension method like so:List list;
using (var s = new MemoryStream(myFile))
{
list = s.ReadLines().ToList();
}...
public static IEnumerable ReadLines(this Stream s)
{
using (var sr = new StreamReader(s))
{
while (!sr.EndOfStream)
{
yield return sr.ReadLine();
}
}
}Code Snippets
List<string> list;
using (var s = new MemoryStream(myFile))
{
list = s.ReadLines().ToList();
}public static IEnumerable<string> ReadLines(this Stream s)
{
using (var sr = new StreamReader(s))
{
while (!sr.EndOfStream)
{
yield return sr.ReadLine();
}
}
}Context
StackExchange Code Review Q#18619, answer score: 7
Revisions (0)
No revisions yet.