Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compressing with GZipStream

Tags:

c#

.net

I am trying to understand why my code doesn't execute as desired. It creates a GZipStream, and then saves the object as compressed file on my hard drive, but the saved file is always 0 bytes.

Now I know how to save a file using GZipStream, but, my question is not how to do it. My question is purely why does this code save 0 bytes (or why FileStream works and memory doesn't).

private void BegingCompression()
{
    var bytes = File.ReadAllBytes(this.fileName);
    using (MemoryStream ms = new MemoryStream(bytes))
    {
        ms.ReadByte();
        using (FileStream fs =new FileStream(this.newFileName, FileMode.CreateNew))
        using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress, false))
        {
            zipStream.Write(bytes, 0, bytes.Length);
        }
    }
}

In regards to the source code, this.fileName = c:\Audio.wav and the newFileName is c:\Audio.wav.gz (but have also tried c:\audio.gz)

like image 308
Dave Avatar asked Jan 12 '13 19:01

Dave


People also ask

What is GZipStream C#?

Provides methods and properties used to compress and decompress streams by using the GZip data format specification.

How do I compress and decompress a file in C#?

To decompress a file, use the same the GZipStream class. Seth the following parameters: source file and the name of the output file. From the source zip file, open a GZipStream. To decompress, use a loop and read as long as you have data in the stream.

Is Brotli better than gzip?

The data is clear that Brotli offers a better compression ratio than GZIP. That is, it compresses your website “more” than GZIP. However, remember that it's not just about the compression ratio, it's also about how long it takes to compress and decompress data.

What is the difference between ZIP and GZIP?

The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though).


1 Answers

  • You do not need a MemoryStream because bytes already has the data to compress.
  • ms.ReadByte() should not be used.
  • When creating the zipStream the output file stream should be used.

Try this:

var bytes = File.ReadAllBytes(this.fileName);
using (FileStream fs =new FileStream(this.newFileName, FileMode.CreateNew))
using (GZipStream zipStream = new GZipStream(fs, CompressionMode.Compress, false))
{
     zipStream.Write(bytes, 0, bytes.Length);
}

EDIT

The original code creates a zero length file because you do not write to the file stream.

like image 193
Richard Schneider Avatar answered Oct 15 '22 01:10

Richard Schneider