Custom Search
Logiclabz
  • Home
  • C#
  • Compress / Gzip files in .Net 2.0 using C# (System.IO.Compression)

Compress / Gzip files in .Net 2.0 using C# (System.IO.Compression)

using System.IO.Compression;

        public class Compress
        {
            string _folderpath="";
            public string folderpath
            {
                get { return _folderpath; }
                set { _folderpath = value; }
            }
            public void compressfolder()
            {

                DirectoryInfo dir=new DirectoryInfo(_folderpath);
                foreach (FileInfo fl in dir.GetFiles())
                {
                   //Open the file as a FileStream object. 
                    FileStream infile = new FileStream(fl.FullName, FileMode.Open,
FileAccess.Read, FileShare.Read);
                    byte[] buffer = new byte[infile.Length];
                    // Read the file to ensure it is readable.
                    int count = infile.Read(buffer, 0, buffer.Length);
                    if (count != buffer.Length)
                    {
                        infile.Close();
                        Console.WriteLine("Test Failed: Unable to read data from file");
                        return;
                    }
                    infile.Close();
                    Stream fs = File.Create(_folderpath + 
Path.ChangeExtension(fl.Name + fl.Extension , ".gz"));
                    // Use the newly created stream for the compressed data.
                    GZipStream gZip = new GZipStream(fs, 
CompressionMode.Compress, true);
                    Console.WriteLine("Compression");
                    gZip.Write(buffer, 0, buffer.Length);
                    // Close the stream.
                    gZip.Close();
                    Console.WriteLine("Original size: {0}, Compressed size: {1}", 
buffer.Length, fs.Length);
                    Console.Read();
                }
            }
	}
the class can used as below
Compress cm = new Compress();
cm.folderpath = @"e:\gsp\";
cm.compressfolder();


Comments


Leave a reply


Do you like this post?