Frage

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. :/

War es hilfreich?

Lösung

Using StreamReader/Writer is not indicated. 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.

There's just no reason to use these classes, GZipStream doesn't care. Use FileStream instead, the only way to be sure that the decompressed bytes are an exact match with the bytes in the original file.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top