如何从Stream对象中读取行的C#代码示例

huangapple go评论77阅读模式
英文:

C# How to read lines from a Stream object

问题

我正在尝试从一个Zip文件中读取前两行.txt文件的内容。我不需要保存整个文件到磁盘。我可以轻松访问zip存档实体:

ZipArchive archive = ZipFile.OpenRead(fileName);

ZipArchiveEntry en = archive.Entries.FirstOrDefault(e =>
        Path.GetExtension(e.Name) == ".txt");

使用

en.Open()

只返回一个流(Stream),而不是StreamReader,因此我无法使用

en.ReadLine()

那么我该如何只读取前两行呢?

谢谢。

英文:

I am trying to read the first two lines from a .txt file inside a Zip file. I don't want or need to save the whole file to disk. I can get to the zip archive entity easily enough:

ZipArchive archive = ZipFile.OpenRead(fileName);

ZipArchiveEntry en = archive.Entries.FirstOrDefault(e =>
        Path.GetExtension(e.Name) == ".txt");

Using

en.Open() 

only returns a Stream, not StreamReader so I can't use

en.ReadLine()

So how can I read just read the first two lines?

Thank you.

答案1

得分: 1

你可以参考这里获取一些知识。

但简而言之,只需创建一个StreamReader实例,参数是从"en.Open()"中获取的流。

using (var reader = new StreamReader(en.Open()))
英文:

You can refer some knowledge from here.

But in short, just create instance of StreamReader with param is Stream you got from "en.Open()"

using (var reader = new StreamReader(en.Open()))

huangapple
  • 本文由 发表于 2023年6月16日 00:47:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483862.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定