简体   繁体   English

如何在C#中使用GZipStream解压缩?

[英]How to decompress with GZipStream in C#?

My problem is that I can't find a solution to decompress a file. 我的问题是我找不到解压缩文件的解决方案。 Compressing a file works without error messages, but I don't know if that's right. 压缩文件时不会出现错误消息,但是我不知道这是否正确。

Here is my code for compressing a file: 这是我压缩文件的代码:

using (StreamReader sr = new StreamReader(File.Open(srcFile, FileMode.Open), true))
using (GZipStream zip = new GZipStream(File.Open(destFile, FileMode.OpenOrCreate), CompressionMode.Compress, false))
using (StreamWriter sw = new StreamWriter(zip, Encoding.UTF8)) {
    while (!sr.EndOfStream) {
        sw.Write((char)sr.Read());
    }
}

Then I tried to decompress the compressed file with following code: 然后,我尝试使用以下代码压缩压缩文件:

using (GZipStream zip = new GZipStream(File.Open(srcFile, FileMode.Open), CompressionMode.Decompress, false))
using (StreamReader sr = new StreamReader(zip, true))
using (StreamWriter sw = new StreamWriter(File.Open(destFile, FileMode.OpenOrCreate), Encoding.UTF8)) {
    while (!sr.EndOfStream) {
        sw.Write((char)sr.Read());
    }
}

The content of the decompressed file wasn't like the content of the source file and I don't know where I've made my mistakes. 解压缩后的文件的内容与源文件的内容不同,而且我不知道自己在哪里犯了错误。

Thanks in advance for your help. 在此先感谢您的帮助。

I'm sorry for my bad English, but English isn't my strength. 我为我的英语不好而感到抱歉,但是英语不是我的强项。 :/ :/

Using StreamReader/Writer is not indicated. 未指示使用StreamReader / Writer。 It will certainly destroy the file content if the file is not a text file. 如果文件不是文本文件,则肯定会破坏文件内容。 And the decompressed file will always have a BOM, it might be missing in the original file. 解压缩后的文件将始终具有BOM表,原始文件中可能会丢失该BOM表。

There's just no reason to use these classes, GZipStream doesn't care. 根本没有理由使用这些类,GZipStream不在乎。 Use FileStream instead, the only way to be sure that the decompressed bytes are an exact match with the bytes in the original file. 而是使用FileStream,这是确保解压缩的字节与原始文件中的字节完全匹配的唯一方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM