GZipStream Class provides methods and properties used to compress and decompress streams. : GZipStream « File Stream « C# / C Sharp






GZipStream Class provides methods and properties used to compress and decompress streams.

  

    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("*.gz"))
            {
                Decompress(fi);
            }
        }
        public static void Compress(FileInfo fi)
        {
            using (FileStream inFile = fi.OpenRead())
            {
                if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden)!= FileAttributes.Hidden & fi.Extension != ".gz")
                {
                    using (FileStream outFile = File.Create(fi.FullName + ".gz"))
                    {
                        using (GZipStream Compress = new GZipStream(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 (GZipStream Decompress = new GZipStream(inFile,CompressionMode.Decompress))
                    {
                    Decompress.CopyTo(outFile);
                    }
                }
            }
        }
    }

   
    
  








Related examples in the same category

1.Use GZipStream to Zip
2.Read all bytes from GZipStream