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);