I want to compress a file before saving physically on the disk.
I tried using compress and decompress methods (MSDN sample code) but all methods require a file which is already physically stored on the disk.
To zip (compress) a file or folder Locate the file or folder that you want to zip. Press and hold (or right-click) the file or folder, select (or point to) Send to, and then select Compressed (zipped) folder. A new zipped folder with the same name is created in the same location.
When performing a Disk Cleanup, you have the option to compress your hard drive. We strongly recommend users do not compress their hard drives or compress their old files.
The easiest way is to open the file as a Stream
and wrap it with a compression API like GZipStream
.
using (var fileStream = File.Open(theFilePath, FileMode.OpenOrCreate) {
using (var stream = new GZipStream(fileStream, CompressionMode.Compress)) {
// Write to the `stream` here and the result will be compressed
}
}
You can use the GZipStream
class not only with a fileName. It is possible to compress a Stream
.
GZipStream Class Provides methods and properties used to compress and decompress streams.
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms,
System.IO.Compression.CompressionMode.Compress);
// now you can save the file to disc
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