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
)
Provides methods and properties used to compress and decompress streams by using the GZip data format specification.
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.
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.
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).
bytes
already has the data to compress. ms.ReadByte()
should not be used. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With