C# 使用压缩文本文件的 StreamReader 只读第一行
我试图只读取压缩 csv 文件的第一行。我使用下面的代码,但收到错误“GZIP 标头中的幻数不正确”。显然,这与 GZIP 和 ZIP 不是相同的格式有关,但即使使用 DotNetZipLib 库或 SharpZip,我似乎也无法使其工作。
using (GZipStream gzipStream = new GZipStream(File.OpenRead(fileName), CompressionMode.Decompress))
{
using(StreamReader sr = new StreamReader(gzipStream))
{
//Matt try something like this as a hint / starting point
While(sr.Read())
{
row = sr.ReadLine();
}
}
}
你们中有人知道如何处理标准 zip 文件(不是 gzip)并将内容流式传输到 StreamReader 对象,以便我可以轻松读取压缩文本文件的第一行吗?我不寻找在打开文本文件之前完全解压缩整个 zip 文件的解决方案。我正在寻找一种与上面类似但可以处理 zip 文件的解决方案。我也不想通过字节数组走极客路线,并且必须从数组中重建第一行,因为这需要了解第一行的确切内容(数据类型、分隔符等)。
谢谢
I am trying to read only the first line of a zipped csv file. I used below code but get the error "The magic number in GZIP header is not correct". Obviously it has to do with the fact that GZIP and ZIP are not identical formats but I do not seem to get it working even when using the DotNetZipLib library or SharpZip.
using (GZipStream gzipStream = new GZipStream(File.OpenRead(fileName), CompressionMode.Decompress))
{
using(StreamReader sr = new StreamReader(gzipStream))
{
//Matt try something like this as a hint / starting point
While(sr.Read())
{
row = sr.ReadLine();
}
}
}
Does any of you know how to handle standard zip files (not gzip) and to stream the content to a StreamReader object so that I can easily read the first line of the zipped text file? I do not look for a solution that completely decompresses the whole zip file before opening the text file. I look for a similar solution as above but one that can handle zip files. I also do not want to go the geeky route through byte arrays and having to reconstruct the first row from the array as it would require knowledge of the exact content of the first row (data types, delimiters,...).
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
例如,Matt 这里是您也可以做的事情,也可以查看此代码示例
这使用 SharpZipLib 库
for example Matt here is something that you could do as well checkout this code sample
This uses SharpZipLib Library
上面的答案对我不起作用(它在运行时抛出错误:“item”为空引用),所以我稍微修改了代码。(一个名为“text.txt”的文本文件被压缩在一个名为“archive.zip”的zip中)这个是在VB.NET中并使用SHARPZIPLIB库(您必须将其导入VB并在公共类mainform之前调用它。
这是代码:
'现在将以下代码放入私有子中(我将其放入私有子中)按钮_单击)
当您运行代码时,将弹出消息框,其中包含在文本文件 text.txt 的第一行中输入的文本
希望这有帮助。干杯!
The above answer didnt work for me (it casted an error at runtime: nullreference for "item") so i modified the code a bit.(a text file called "text.txt" is zipped in a zip called "archive.zip") This one is in VB.NET and uses SHARPZIPLIB library(you must import it into VB and call it before public class mainform.
here is the code :
'now put the following code in a private sub ( i put it in private sub button_click)
When u run the code, The message box will popup with the text that is entered in the first line of a text file text.txt
Hope this helps. Cheers!