ReadAllLines为Stream对象? [英] ReadAllLines for a Stream object?
本文介绍了ReadAllLines为Stream对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有存在 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键&LT;&GT;
部分是阅读一次以上时应付,并且避免留下流开不必要的。你可以很容易包装,当然在一个方法code了。
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
...
这篇关于ReadAllLines为Stream对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文