Zip compression and decompression can be achieved in. NET in a variety of ways: 1, using the System.IO.Packaging program; 2, the use of third-party class library; 3, through the System.IO.Compression namespace in the new ziparchive, the ZipFile class and other implementation
One, using System.IO.Packaging program compression and decompression
Packages are an abstract class that can be used to organize objects into a single entity in a defined physical format for portability and efficient access. The zip file is the primary physical format of the package. Other package implementations can use other physical formats such as XML documents, databases, or Web services. Similar to file systems, items contained in a package are referenced in folders and files in a hierarchical organization. Although the wrapper is an abstract class, the Package.Open method uses the ZipPackage derived class by default.
The System.IO.Packaging program needs to add a reference to the windowsbase when it is used under the WindowsBase.dll assembly.
1. Compress the entire folder into compressed
Code///< summary >
Add a folder and its subfolders a package along
</Summary >
<param name = "folder Name" > Add Folder </param>
<param name = "Compressedfilename" > Create Package </param>
<param name = "Overrideexisting" > Overwrite exsisitng file </param>
< return > </return >
Static Boolean Packagefolder (String folder name, String Compressedfilename, Boolean overrideexisting)
{
if (Foldername.endswith (@ "\"))
FOLDERNAME = Foldername.remove (foldername.length-1);
Boolean result = FALSE;
if (directory.exists (folder name)! )
{
return the result;
}
(! Overrideexisting && file.exists (compressedfilename)) if
{
return the result;
}
Try
{
Use (package = Package.Open (compressedfilename,filemode.create))
{
var filelist = directory.enumeratefiles (folder name, "*", searchoption.alldirectories);
The foreach (in the filelist string file name)
{
The path in the package is a subfolder after all the folder names
String Pathinpackage;
Pathinpackage = path.getdirectoryname (file name). Replace (folder name, String.Empty) + "/" + path.getfilename (file name);
Uri parturidocument = Packurihelper.createparturi (new Uri (pathinpackage,urikind.relative));
The PackagePart packagepartdocument = package. CreatePart (Parturidocument, "", compressionoption.maximum);
Use (FILESTREAM FILESTREAM = new FILESTREAM (file name, FileMode.Open,FileAccess.Read))
{
Filestream.copyto (Packagepartdocument.getstream ());
}
}
}
result = true;
}
Catch up (Exception five)
{
Throws a new exception ("Error zipping folder" folder name +,e);
}
return the result;
}
2. Add a single file to a compressed file
The code///< summary >
Compress the file into a zip file as a container Store
</Summary >
<param name = "file name" > file compression </param>
<param name = "Compressedfilename" > archive file </param>
<param name = "Overrideexisting" > Overwrite existing file </param>
< return > </return >
Static Boolean PackageFile (string filename, String compressedfilename, Boolean overrideexisting)
{
Boolean result = FALSE;
if (file.exists (filename)! )
{
return the result;
}
(! Overrideexisting && file.exists (compressedfilename)) if
{
return the result;
}
Try
{
Uri parturidocument = Packurihelper.createparturi (new Uri (Path.getfilename (filename), urikind.relative));
Use (package = Package.Open (compressedfilename,filemode.openorcreate))
{
if (package. Partexists (parturidocument))
{
Package. Deletepart (parturidocument);
}
The PackagePart packagepartdocument = package. CreatePart (Parturidocument, "", compressionoption.maximum);
Use (FILESTREAM FILESTREAM = new FILESTREAM (file name, FileMode.Open,FileAccess.Read))
{
Filestream.copyto (Packagepartdocument.getstream ());
}
}
result = true;
}
Catch up (Exception five)
{
Throws a new exception ("Error compression and decryption file" + file name, E);
}
return the result;
} 3, extract the compressed files
Code///< summary >
Extract of the container zip code. Note: The container must be created as an Open Packaging Convention (OPC) specification
</Summary >
<param name = "folder Name" > folder unpacking package </param>
<param name = "Compressedfilename" > Package file </param>
<param name = "Overrideexisting" > Overwrite existing file </param>
< return > </return >
Static Boolean Uncompressfile (String folder name, String Compressedfilename, Boolean overrideexisting)
{
Boolean result = FALSE;
Try
{
if (file.exists (compressedfilename)! )
{
return the result;
}
DirectoryInfo DirectoryInfo = new DirectoryInfo (folder name);
if (! directoryinfo.exists)
Directoryinfo.create ();
Use (package = Package.Open (Compressedfilename,filemode.open,fileaccess.read))
{
The foreach (PackagePart of the PackagePart in Package.getparts ())
{
Extractpart (PackagePart, folder name, overrideexisting);
}
}
result = true;
}
Catch up (Exception five)
{
Throws a new exception ("Error extracting file" + compressedfilename,e);
}
if (Directory.Exists (Path.getdirectoryname (stringpart))! )
Directory.CreateDirectory (Path.getdirectoryname (Stringpart));
if (! Overrideexisting && file.exists (Stringpart))
Return
Used (FILESTREAM FILESTREAM = new FILESTREAM (stringpart,filemode.create))
{
Packagepart.getstream () CopyTo from (FILESTREAM).
}
}
Using the package compression file automatically generates the [content]. XML in the compressed file, which describes the file formats supported by the compressed file decompression.
Code <? XML version = "1.0" encoding = "UTF-8"? >
< type of xmlns = "Http://schemas.openxmlformats.org/package/2006/content-types" >
< default extension = "vsixmanifest" contenttype = "text/XML"/>
< default extension = "DLL" contenttype = "application/eight-bit byte-stream"/>
< default extension = "PNG" for contenttype = "application/eight-bit byte stream"/>
< default extension = "TXT" for contenttype = "Text/plain"/>
< default extension = "pkgdef" contenttype = "TEXT/plain"/>
</type > Similarly, if the compressed file does not contain the [content]. xml file, or the [content]. xml file does not contain a description of the extension (manually added [content]. XML is also possible), the file cannot be decompressed. Two, the use of third-party class library compression compression and decompression using the comparison of SharpZipLib and DotNetZip.
1,sharpziplib, also known as the "#ziplib", is based on the GPL open source, which supports compression and decompression of zip,gzip tar and BZip2 compression.
Support for. NET 1.1,.net 2.0 (3.5,4.0).
(1) Zip compression
Codepublic Static Invalid ZIP code (string srcfile, string dstfile,int buffer size)
{
The FileStream filestreamin = new FileStream
(Srcfile,filemode.open,fileaccess.read);
The FileStream filestreamout = new FileStream
(Dstfile,filemode.create,fileaccess.write);
Zipoutputstream Zipoutstream = new Zipoutputstream (filestreamout);
byte [] buffer = new byte < buffer size/>;
ZipEntry of the entry = new ZipEntry (Path.getfilename (srcfile));
Zipoutstream.putnextentry (input);
int size;
Do
{
Size = Filestreamin.read (buffer, 0,buffer.length);
Zipoutstream.write (buffer, 0, size);
} and (Size > 0);
Zipoutstream.close ();
Filestreamout.close ();
Filestreamin.close ();
} (2) decompression zipcodepublic static Invalid decompression (string srcfile, dstfile,int buffer size)
{
The FileStream filestreamin = new FileStream
(Srcfile,filemode.open,fileaccess.read);
Zipinputstream Zipinstream = new Zipinputstream (filestreamin);
ZipEntry entry = Zipinstream.getnextentry ();
The FileStream filestreamout = new FileStream
(dstfile + @ "\" + entry. Name,filemode.create,fileaccess.write);
int size;
byte [] buffer = new byte < buffer size/>;
Do
{
Size = Zipinstream.read (buffer, 0,buffer.length);
Filestreamout.write (buffer, 0, size);
} and (Size > 0);
Zipinstream.close ();
Filestreamout.close ();
Filestreamin.close ();
} 2,dotnetlib, is based on "WS-PL" open source, using relatively simple (1) Compression code use (zipper using ZipFile = new ZipFile ())
{
Zip. AddFile (the "Readme.txt");
Zip.addfile ("7440-n49th.png");
Zip. AddFile ("2008_annual_report.pdf");
Zip. Save ("Archive.zip");
} (2) Decompression codeprivate Invalid myextract ()
{
String ziptounpack = "C1p3sml.zip";
String unpackdirectory = "Unzip the file";
Use (ZIP1 using ZipFile = Zipfile.read (ziptounpack))
{
Here we extract each entry, but we can conditionally extract
Depending on the entry name, size, date, check box status, etc.//
The foreach (ZipEntry e in ZIP1)
{
E.extract (unpackdirectory,extractexistingfileaction.overwritesilently);
}
}
}
Third, in. NET 4.5 using Ziparchive, ZipFile and other classes of compression and decompression
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.