DeflateStream provides methods and properties for compressing and decompressing streams using the Deflate algorithm.
using System;
using System.IO;
using System.IO.Compression;
public class Program
{
public static void Main()
{
string dirpath = @"c:\";
DirectoryInfo di = new DirectoryInfo(dirpath);
foreach (FileInfo fi in di.GetFiles())
{
Compress(fi);
}
foreach (FileInfo fi in di.GetFiles("*.cmp"))
{
Decompress(fi);
}
}
public static void Compress(FileInfo fi)
{
using (FileStream inFile = fi.OpenRead())
{
if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden)!= FileAttributes.Hidden & fi.Extension != ".cmp")
{
using (FileStream outFile = File.Create(fi.FullName + ".cmp"))
{
using (DeflateStream Compress = new DeflateStream(outFile, CompressionMode.Compress))
{
inFile.CopyTo(Compress);
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fi.Name, fi.Length.ToString(), outFile.Length.ToString());
}
}
}
}
}
public static void Decompress(FileInfo fi)
{
using (FileStream inFile = fi.OpenRead())
{
string curFile = fi.FullName;
string origName = curFile.Remove(curFile.Length - fi.Extension.Length);
using (FileStream outFile = File.Create(origName))
{
using (DeflateStream Decompress = new DeflateStream(inFile,CompressionMode.Decompress))
{
Decompress.CopyTo(outFile);
Console.WriteLine("Decompressed: {0}", fi.Name);
}
}
}
}
}
Related examples in the same category