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)
bytesalready has the data to compress.ms.ReadByte()should not be used.zipStreamthe output file stream should be used.Try this:
EDIT
The original code creates a zero length file because you do not write to the file stream.