Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress a file before saving on the disk?

Tags:

c#

c#-4.0

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.

like image 827
NIlesh Lanke Avatar asked Jan 31 '12 08:01

NIlesh Lanke


People also ask

How do I compress a file before saving it?

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.

Should I compress files to save disk space?

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.


2 Answers

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
  }
}
like image 152
JaredPar Avatar answered Nov 14 '22 23:11

JaredPar


Description

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.

Sample

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

More Information

  • MSDN - GZipStream Class
like image 23
dknaack Avatar answered Nov 14 '22 23:11

dknaack