<?xml version="1.0" encoding="utf-8" ?> <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"> <Default Extension="vsixmanifest" ContentType="text/xml" /> <Default Extension="dll" ContentType="application/octet-stream" /> <Default Extension="png" ContentType="application/octet-stream" /> <Default Extension="txt" ContentType="text/plain" /> <Default Extension="pkgdef" ContentType="text/plain" /> </Types>
同样,如果zip文件不包含[Content_Type].xml文件,或者[Content_Type].xml文件不包含所对应扩展名的描述(手动添加的[Content_Type].xml也是可以),将无法解压文件。
二、使用第三方类库
zip的压缩和解压使用比较的有SharpZipLib和DotNetZip。
1、SharpZipLib,也称为“#ziplib”,基于GPL开源,支持Zip,GZip,Tar和BZip2的压缩和解压缩。
支持.NET 1.1,NET 2.0(3.5、4.0).
(1)zip压缩
public static void Zip(string SrcFile, string DstFile, int BufferSize) { FileStream fileStreamIn = new FileStream (SrcFile, FileMode.Open, FileAccess.Read); FileStream fileStreamOut = new FileStream (DstFile, FileMode.Create, FileAccess.Write); ZipOutputStream zipOutStream = new ZipOutputStream(fileStreamOut); byte[] buffer = new byte<buffersize />; ZipEntry entry = new ZipEntry(Path.GetFileName(SrcFile)); zipOutStream.PutNextEntry(entry); int size; do { size = fileStreamIn.Read(buffer, 0, buffer.Length); zipOutStream.Write(buffer, 0, size); } while (size > 0); zipOutStream.Close(); fileStreamOut.Close(); fileStreamIn.Close(); }
(2)解压zip
public static void UnZip(string SrcFile, string DstFile, int BufferSize) { FileStream fileStreamIn = new FileStream (SrcFile, FileMode.Open, FileAccess.Read); ZipInputStream zipInStream = new ZipInputStream(fileStreamIn); ZipEntry entry = zipInStream.GetNextEntry(); FileStream fileStreamOut = new FileStream (DstFile + @"\" + entry.Name, FileMode.Create, FileAccess.Write); int size; byte[] buffer = new byte<buffersize />; do { size = zipInStream.Read(buffer, 0, buffer.Length); fileStreamOut.Write(buffer, 0, size); } while (size > 0); zipInStream.Close(); fileStreamOut.Close(); fileStreamIn.Close(); }
2、DotNetLib,是基于”WS-PL”开源,使用比较简单
(1)压缩
using (ZipFile zip = new ZipFile()) { zip.AddFile("ReadMe.txt"); zip.AddFile("7440-N49th.png"); zip.AddFile("2008_Annual_Report.pdf"); zip.Save("Archive.zip"); }
(2)解压
private void MyExtract() { string zipToUnpack = "C1P3SML.zip"; string unpackDirectory = "Extracted Files"; using (ZipFile zip1 = ZipFile.Read(zipToUnpack)) { // here, we extract every entry, but we could extract conditionally // based on entry name, size, date, checkbox status, etc. foreach (ZipEntry e in zip1) { e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently); } } }
三、在.NET 4.5使用ZipArchive、ZipFile等类压缩和解压
static void Main(string[] args) { string ZipPath = @"c:\users\exampleuser\start.zip"; string ExtractPath = @"c:\users\exampleuser\extract"; string NewFile = @"c:\users\exampleuser\NewFile.txt"; using (ZipArchive Archive = ZipFile.Open(ZipPath, ZipArchiveMode.Update)) { Archive.CreateEntryFromFile(NewFile, "NewEntry.txt"); Archive.ExtractToDirectory(ExtractPath); } }