2

I have a System.IO.Stream that I'm getting content from (a file). I do the following:

using (var reader = new StreamReader(mystream))
{
  var filecontent = reader.ReadLine();
}

That only captures a single line. I'd like to put each line into a List<String>. How can that be done?

4thSpace
  • 43,672
  • 97
  • 296
  • 475
  • 5
    Why not use [`File.ReadAllLines`](https://msdn.microsoft.com/en-us/library/system.io.file.readalllines(v=vs.110).aspx)? (since you say you're getting the content from a file) – p.s.w.g Jun 08 '16 at 16:45
  • Where do you get File from? I only have a Stream. – 4thSpace Jun 08 '16 at 16:47
  • ReadAllLines is appropriate for small files, but loads everything into memory. This is a good idea in this specific case that the OP wants a `List`, but future readers be aware that it's not always the best way to "read each line of file in loop". – Eric J. Jun 08 '16 at 16:47
  • @4thSpace: System.IO.File.ReadAllLines https://msdn.microsoft.com/en-us/library/system.io.file.readalllines(v=vs.110).aspx – Eric J. Jun 08 '16 at 16:48
  • Linked as duplicate post shows multiple ways to read files/streams (or use iterator shown in http://stackoverflow.com/questions/1271225/c-sharp-reading-a-file-line-by-line)... But I'd recommend reading on some C# basics first like loops (`while`/`for`) as it seem to be main problem in this question. – Alexei Levenkov Jun 08 '16 at 17:04

2 Answers2

2

inside the using add

while (reader.Peek() >= 0){
   list.add(reader.readline);
}
rojobo
  • 476
  • 4
  • 16
2

If you have a file :

 List<string> allLines = File.ReadAllLines(fileName).ToList();

In case of you have steam instead of a file :

List<string> allLines = new List<string>();
    using (StreamReader reader = new StreamReader(stream))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
        allLines.Add(line); // Add to list.     
        }
    }
Maverick
  • 1,396
  • 5
  • 22
  • 42