How to compress multiple files/folders (GZipStream and C #)

Source: Internet
Author: User
Tags zip

With the System.IO.Compression class added to the. Net Framework 2.0 for compressing/decompressing files (GZipStream methods), let's look at a simple example.

Code1:

1 public static void Compress (String filePath, String zippath)
2 {
3 FileStream sourcefile = File.openread (FilePath);
4 FileStream destinationfile = File.create (Zippath);
5 byte[] buffer = new Byte[sourcefile.length];
6 GZipStream zip = null;
7 Try
8 {
9 sourcefile.read (buffer, 0, buffer. Length);
Ten zip = new GZipStream (destinationfile, compressionmode.compress);
One zip. Write (buffer, 0, buffer.) Length);
12}
Catch
14 {
throw;
16}
Finally
18 {
Zip. Close ();
Sourcefile.close ();
Destinationfile.close ();
22}
23}
24
The public static void decompress (string zippath,string FilePath)
26 {
FileStream sourcefile = File.openread (Zippath);
28
-String path = Filepath.replace (Path.getfilename (FilePath), "");
30
if (! Directory.Exists (PATH))
Directory.CreateDirectory (path);
33
FileStream destinationfile = file.create (FilePath);
GZipStream unzip = null;
byte[] buffer = new Byte[sourcefile.length];
Panax Notoginseng Try
38 {
Unzip = new GZipStream (SourceFile, compressionmode.decompress, true);
int numberofbytes = unzip. Read (buffer, 0, buffer.) Length);
41
Destinationfile.write (buffer, 0, numberofbytes);
43}
Catch
45 {
throw;
47}
Finally
49 {
Sourcefile.close ();
Wuyi Destinationfile.close ();
Unzip. Close ();
53}
54}

Case:

1. Compress

1      string folder = Path.Combine(Server.MapPath("~"), "TestCompress");
2      string file = "file1.txt";
3      string zip = "myzip";
4
5      SampleCompress.Compress(Path.Combine(folder, file), Path.Combine(folder, zip));

2. Decompression

1      string folder = Path.Combine(Server.MapPath("~"), "TestCompress");
2      string file = "file1.txt";
3      string zip = "myzip";
4
5      SampleCompress.Decompress(Path.Combine(folder, zip),
Path.Combine (Path.Combine (folder, "Zipfolder"), file);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.