使用 C# 解压缩 .gz 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1348198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:28:32  来源:igfitidea点击:

Unzipping a .gz file using C#

c#

提问by Ed.

I have a tarred gunzip file called ZippedXmls.tar.gz which has 2 xmls inside it. I need to programmatically unzip this file and the output should be 2 xmls copied in a folder.

我有一个名为 ZippedXmls.tar.gz 的 tarred gunzip 文件,其中包含 2 个 xml。我需要以编程方式解压缩此文件,输出应为复制到文件夹中的 2 个 xml。

How do I achieve this using C#?

我如何使用 C# 实现这一点?

采纳答案by Charlie Salts

I've used .Net's built-in GZipStreamfor gzipping byte streams and it works just fine. I suspect that your files are tarred first, before being gzipped.

我已经使用 .Net 的内置GZipStream压缩字节流,它工作得很好。我怀疑您的文件在被 gzip 之前首先被压缩。

You've asked for code, so here's a sample, assuming you have a single file that is zipped:

您已要求提供代码,因此这里有一个示例,假设您有一个已压缩的文件:

FileStream stream = new FileStream("output.xml", FileMode.Create); // this is the output
GZipStream uncompressed = new GZipStream(stream, CompressionMode.Decompress);

uncompressed.Write(bytes,0,bytes.Length); // write all compressed bytes
uncompressed.Flush();
uncompressed.Close();

stream.Dispose();

Edit:

编辑:

You've changed your question so that the file is a tar.gz file - technically my answer is not applicable to your situation, but I'll leave it here for folks who want to handle .gz files.

您已经更改了您的问题,因此该文件是 tar.gz 文件 - 从技术上讲,我的回答不适用于您的情况,但我会将其留在这里供想要处理 .gz 文件的人使用。

回答by Stefan Egli

sharpziplibshould be able to do this

sharpziplib应该能够做到这一点

回答by Lee Richardson

I know this question is ancient, but search engines redirect here for how to extract gzip in C#, so I thought I'd provide a slightly more recent example:

我知道这个问题很古老,但是搜索引擎重定向到这里以了解如何在 C# 中提取 gzip,所以我想我会提供一个稍微更新的示例:

using (var inputFileStream = new FileStream("c:\myfile.xml.gz", FileMode.Open))
using (var gzipStream = new GZipStream(inputFileStream, CompressionMode.Decompress))
using (var outputFileStream = new FileStream("c:\myfile.xml", FileMode.Create))
{
    await gzipStream.CopyToAsync(outputFileStream);
}

For what should be the simpler question of how to untar see: Decompress tar files using C#

对于如何解压缩的更简单的问题应该是什么,请参阅:Decompress tar files using C#