Are there any built-in classes/examples for version 4.0 to compress specific files from a directory? I found an example on MSDN which uses the compression class but it is only for version 4.5 & above.
You can use GZipStream
and DeflateStream
classes which includes also .NET Framework 4.
Check How to: Compress Files
from MSDN.
Use the System.IO.Compression.GZipStream class to compress and decompress data. You can also use the System.IO.Compression.DeflateStream class, which uses the same compression algorithm; however, compressed GZipStream objects written to a file that has an extension of .gz can be decompressed using many common compression tools.
An example from here:
FileStream sourceFileStream = File.OpenRead("sitemap.xml");
FileStream destFileStream = File.Create("sitemap.xml.gz");
GZipStream compressingStream = new GZipStream(destFileStream,
CompressionMode.Compress);
byte[] bytes = new byte[2048];
int bytesRead;
while ((bytesRead = sourceFileStream.Read(bytes, 0, bytes.Length)) != 0)
{
compressingStream.Write(bytes, 0, bytesRead);
}
sourceFileStream.Close();
compressingStream.Close();
destFileStream.Close();
FileStream sourceFileStream = File.OpenRead("sitemap.xml.gz");
FileStream destFileStream = File.Create("sitemap.xml");
GZipStream decompressingStream = new GZipStream(sourceFileStream,
CompressionMode.Decompress);
int byteRead;
while((byteRead = decompressingStream.ReadByte()) != -1)
{
destFileStream.WriteByte((byte)byteRead);
}
decompressingStream.Close();
sourceFileStream.Close();
destFileStream.Close();
I've done a lot of file compression work over the years and by far the best option I found is to use DotNetZip
http://dotnetzip.codeplex.com
Better than GZipStream
and the other BCL offerings. It has a friendly API and provides significant functionality.
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