ReadAllLines for a Stream object?

后端 未结 6 805
醉酒成梦
醉酒成梦 2020-12-01 11:31

There exists a File.ReadAllLines but not a Stream.ReadAllLines.

using (Stream stream = Assembly.GetExecutingAssembly().GetManifestR         


        
6条回答
  •  不思量自难忘°
    2020-12-01 12:30

    You can write a method which reads line by line, like this:

    public IEnumerable ReadLines(Func streamProvider,
                                         Encoding encoding)
    {
        using (var stream = streamProvider())
        using (var reader = new StreamReader(stream, encoding))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                yield return line;
            }
        }
    }
    

    Then call it as:

    var lines = ReadLines(() => Assembly.GetExecutingAssembly()
                                        .GetManifestResourceStream(resourceName),
                          Encoding.UTF8)
                    .ToList();
    

    The Func<> part is to cope when reading more than once, and to avoid leaving streams open unnecessarily. You could easily wrap that code up in a method, of course.

    If you don't need it all in memory at once, you don't even need the ToList...

提交回复
热议问题