Stream 对象的 ReadAllLines? [英] ReadAllLines for a Stream object?

查看:17
本文介绍了Stream 对象的 ReadAllLines?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

存在 File.ReadAllLines 但不存在 Stream.ReadAllLines.

using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Test_Resources.Resources.Accounts.txt"))
using (StreamReader reader = new StreamReader(stream))
{
    // Would prefer string[] result = reader.ReadAllLines();
    string result = reader.ReadToEnd();
}

有没有办法做到这一点,还是我必须手动逐行遍历文件?

Does there exist a way to do this or do I have to manually loop through the file line by line?

推荐答案

你可以写一个逐行读取的方法,像这样:

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

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

然后将其称为:

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

Func<> 部分是为了应对多次读取时的情况,并避免不必要地打开流.当然,您可以轻松地将该代码封装在一个方法中.

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.

如果您一次不需要所有的内存,您甚至不需要 ToList...

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

这篇关于Stream 对象的 ReadAllLines?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆