I've been trying to implement a compression method in one of my programs. I want it to take in a stream, compress it, and return the compressed stream (It returns a stream because I want to be able to pass the stream to another function without having to save it to a file and re-read it later). I had a working test version based on the msdn example for GZipStream, and this is what I came up with when I tried to convert it to taking in and returning streams:
public static Stream compress(Stream fileToCompress)
{
using (MemoryStream compressedFileStream = new MemoryStream())
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
{
fileToCompress.CopyTo(compressionStream);
return compressionStream;
}
}
}
Saving the returned stream to a file (in another method) results in a file of 0 bytes being created (pretty efficient compression, huh?).
I've tried looking for other solutions, but I haven't been able to find any that use streams, and my attempts to convert run into the same problem.
Edit: Just for the record, I have tried using DeflateStream to the same results.
EDIT2: Turns out it was the test program not saving properly. Thanks for the help.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…