IntroductionIn this code snippet help to compress files in .NET 2.0 or later version using C#. first i have create a new windows application using VS 2008, then i have add a textbox and two buttons. One button for compress and another button for decompress.finally i have added OpenDialog to select the file to compress. see below screen shot. Then add code to compress files under the Compress button click.before that you have add a reference to access Compress class in .net using System.IO;using System.IO.Compression; Once we added reference write code for select the source files to selection button click event. private void btnOK_Click(object sender, EventArgs e){OpenFileDialog fdialog = new OpenFileDialog();if (fdialog.ShowDialog() == DialogResult.OK){txts.Text = fdialog.FileName;}}Compress Button click Eventprivate void btnCompress_Click(object sender, EventArgs e){try{// get information for the source fileFileInfo info = new FileInfo(txts.Text);if (info.Extension != ".gz"){byte[] data;using (FileStream sourcestream = File.OpenRead(info.FullName)){data = new byte[sourcestream.Length];// read source data to byte arraysourcestream.Read(data, 0, (int)sourcestream.Length);}using (FileStream dstream = File.Create((info.FullName + ".gz"))){using (GZipStream gzstream = new GZipStream(dstream, CompressionMode.Compress)){// write data to sys using compressgzstream.Write(data, 0, data.Length);}}}}catch (Exception ex){throw;}} In Above code, just simple logic has added, first we have to read the source files and create byte array of the source data. Then i have create destination stream to from the same file with ".gz". The .GZ is extension of the new compression file. then write data using compression stream with mode of Compression to same location. DeCompress Button click Eventprivate void btnDCompress_Click(object sender, EventArgs e){try{FileInfo info = new FileInfo(txts.Text);if (info.Extension == ".gz"){byte[] data;using (FileStream sourcestream = File.OpenRead(info.FullName)){data = new byte[sourcestream.Length];sourcestream.Read(data, 0, (int)sourcestream.Length);}// the file name like abc.exe.gz// here i have remove last extension from the path.string destionationFileName = info.FullName.Remove(info.FullName.Length - info.Extension.Length);using (FileStream dstream = File.Create(destionationFileName)){using (GZipStream gzstream = new GZipStream(dstream, CompressionMode.Decompress)){gzstream.Write(data, 0, data.Length);}}}}catch (Exception ex){throw;}} In above event,we have done just bi-direction task with mode of DeCompression. that's all enjoy the file compression with few lines of code. Sample Project SourceDownload source files -37 kb |