1

Given the code below, why is the decompression not working? "NewFile2.txt" should have the original, decompressed text, but the file is just blank.

ioTests.CompressFile(@"c:\newfile.txt", @"c:\newfile.txt.gz");
ioTests.DecompressFile(@"c:\newfile.txt.gz", @"c:\newfile2.txt");

public void CompressFile(string inFileName, string outFileName)
{
    FileStream inFile = new FileStream(inFileName, FileMode.Open);
    FileStream outFile = new FileStream(outFileName, FileMode.Create);

    GZipStream compStream = new GZipStream(outFile, CompressionMode.Compress);

    int theByte = inFile.ReadByte();

    while (theByte != -1)
    {
        compStream.WriteByte((byte)theByte);
        theByte = inFile.ReadByte();
    }

    compStream.Close();
}

public void DecompressFile(string inFileName, string outFileName)
{
    FileStream inFile = new FileStream(inFileName, FileMode.Open);
    FileStream outFile = new FileStream(outFileName, FileMode.CreateNew);

    GZipStream compStream = new GZipStream(inFile, CompressionMode.Decompress);

    int theByte = compStream.ReadByte();

    while (theByte != -1)
    {
        outFile.WriteByte((byte)theByte);

        theByte = compStream.ReadByte();
    }

    compStream.Close();
}
LarsTech
  • 80,625
  • 14
  • 153
  • 225
richard
  • 12,263
  • 23
  • 95
  • 151

3 Answers3

4
outFile.Flush(); // after your loop
Waleed
  • 3,105
  • 2
  • 24
  • 31
  • You're my favorite dude tonight! Thanks! That worked! (I'm such an idiot for not seeing that. I was going cross-eyed) – richard Jun 15 '11 at 07:23
  • @Richard : LoL, we all do such kind of crap when doing night coding :P – Waleed Jun 15 '11 at 07:24
2

I prefer

outFile.Close() 

as that flushes the stream and calls the Dispose method, releasing allocated resources.

Skizz
  • 69,698
  • 10
  • 71
  • 108
2

Since the streams you use implement the IDisposable interface, you should Dispose() / Close() your classes, or use the using statement to do this automatically:

    using (FileStream inFile = new FileStream(inFileName, FileMode.Open))
    using (FileStream outFile = new FileStream(outFileName, FileMode.Create))

    using (GZipStream compStream = new GZipStream(outFile, CompressionMode.Compress)) {

        int theByte = inFile.ReadByte();
        // ... Rest of your code

    }

This roughly translates to:

    try {
       FileStream inFile = new FileStream(inFileName, FileMode.Open);
       FileStream outFile = new FileStream(outFileName, FileMode.Create);
       GZipStream compStream = new GZipStream(outFile, CompressionMode.Compress);

        int theByte = inFile.ReadByte();
        // ... Rest of your code

    } finally {
        if (inFile != null) inFile.Dispose();
        if (outFile != null) outFile.Dispose();
        if (compStream != null) compStream.Dispose();
    }
GvS
  • 52,015
  • 16
  • 101
  • 139