在.NET可以通过多种方式实现zip的压缩和解压:1、使用System.IO.Packaging;2、使用第三方类库;3、通过 System.IO.Compression 命名空间中新增的ZipArchive、ZipFile等类实现。
一、使用System.IO.Packaging压缩和解压
Package
为一个抽象类,可用于将对象组织到定义的物理格式的单个实体中,从而实现可移植性与高效访问。ZIP 文件是
Package
的主物理格式。 其他
Package
实现可以使用其他物理格式(如 XML 文档、数据库或 Web 服务。与文件系统类似,在分层组织的文件夹和文件中引用
Package
中包含的项。虽然
Package
是抽象类,但
Package.Open
方法默认使用
ZipPackage
派生类。
System.IO.Packaging在WindowsBase.dll程序集下,使用时需要添加对WindowsBase的引用。
1、将整个文件夹压缩成zip
/// <summary>
/// Add a folder along with its subfolders to a Package
/// </summary>
/// <param name="folderName">The folder to add</param>
/// <param name="compressedFileName">The package to create</param>
/// <param name="overrideExisting">Override exsisitng files</param>
/// <returns></returns>
static bool PackageFolder(string folderName, string compressedFileName, bool overrideExisting)
if (folderName.EndsWith(@"\"))
folderName = folderName.Remove(folderName.Length - 1);
bool result = false;
if (!Directory.Exists(folderName))
return result;
if (!overrideExisting && File.Exists(compressedFileName))
return result;
using (Package package = Package.Open(compressedFileName, FileMode.Create))
var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);
foreach (string fileName in fileList)
//The path in the package is all of the subfolders after folderName
string pathInPackage;
pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName);
Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative));
PackagePart packagePartDocument = package.CreatePart(partUriDocument,"", CompressionOption.Maximum);
using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
fileStream.CopyTo(packagePartDocument.GetStream());
result = true;
catch (Exception e)
throw new Exception("Error zipping folder " + folderName, e);
return result;
}
View Code
注:当文件夹名或文件名包含空格时会乱码,有解决办法请赐教
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="folderName">要添加的文件夹</param>
/// <param name="zipFilePath">生成压缩文件的路径,为空则默认与被压缩文件夹同一级目录,名称为:文件夹名+.zip</param>
/// <returns></returns>
public static bool PackageFolder(string folderName, string zipFilePath)
if (folderName.EndsWith(@"\"))
folderName = folderName.Remove(folderName.Length - 1);
bool result = false;
if (!Directory.Exists(folderName))
return result;
//压缩文件名为空时使用文件夹名+.zip
if (string.IsNullOrEmpty(zipFilePath))
if (folderName.EndsWith("\\"))
folderName = folderName.Substring(0, folderName.Length - 1);
zipFilePath = folderName + ".zip";
var fileList = Directory.GetFiles(folderName, "*", SearchOption.AllDirectories);
using (Package package = Package.Open(zipFilePath, FileMode.OpenOrCreate))
string pathInPackage;
foreach (string fileName in fileList)
pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "\\" + Path.GetFileName(fileName);
Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.RelativeOrAbsolute));
PackagePart packagePartDocument = package.CreatePart(partUriDocument,"", CompressionOption.Maximum);
using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
fileStream.CopyTo(packagePartDocument.GetStream());
result = true;
catch (Exception e)
LogHelper.Error(e);
return result;
}
View Code
2、将单个文件添加到zip文件中
/// <summary>
/// Compress a file into a ZIP archive as the container store
/// </summary>
/// <param name="fileName">The file to compress</param>
/// <param name="compressedFileName">The archive file</param>
/// <param name="overrideExisting">override existing file</param>
/// <returns></returns>
static bool PackageFile(string fileName, string compressedFileName, bool overrideExisting)
bool result = false;
if (!File.Exists(fileName))
return result;
if (!overrideExisting && File.Exists(compressedFileName))
return result;
Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(Path.GetFileName(fileName), UriKind.Relative));
using (Package package = Package.Open(compressedFileName, FileMode.OpenOrCreate))
if (package.PartExists(partUriDocument))
package.DeletePart(partUriDocument);
PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum);
using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
fileStream.CopyTo(packagePartDocument.GetStream());
result = true;
catch (Exception e)
throw new Exception("Error zipping file " + fileName, e);
return result;
}
View Code
3、zip文件解压
/// <summary>
/// Extract a container Zip. NOTE: container must be created as Open Packaging Conventions (OPC) specification
/// </summary>
/// <param name="folderName">The folder to extract the package to</param>
/// <param name="compressedFileName">The package file</param>
/// <param name="overrideExisting">override existing files</param>
/// <returns></returns>
static bool UncompressFile(string folderName, string compressedFileName, bool overrideExisting)
bool result = false;
if (!File.Exists(compressedFileName))
return result;
DirectoryInfo directoryInfo = new DirectoryInfo(folderName);
if (!directoryInfo.Exists)
directoryInfo.Create();
using (Package package = Package.Open(compressedFileName, FileMode.Open, FileAccess.Read))
foreach (PackagePart packagePart in package.GetParts())
ExtractPart(packagePart, folderName, overrideExisting);
result = true;
catch (Exception e)
throw new Exception("Error unzipping file " + compressedFileName, e);
return result;
static void ExtractPart(PackagePart packagePart, string targetDirectory, bool overrideExisting)
string stringPart = targetDirectory + HttpUtility.UrlDecode(packagePart.Uri.ToString()).Replace('\\', '/');
if (!Directory.Exists(Path.GetDirectoryName(stringPart)))
Directory.CreateDirectory(Path.GetDirectoryName(stringPart));
if (!overrideExisting && File.Exists(stringPart))
return;
using (FileStream fileStream = new FileStream(stringPart, FileMode.Create))
packagePart.GetStream().CopyTo(fileStream);
}
View Code
使用
Package
压缩文件会在zip文件自动生成[Content_Type].xml,用来描述zip文件解压支持的文件格式。
<?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>
View Code
同样,如果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;
size = fileStreamIn.Read(buffer, 0, buffer.Length);
zipOutStream.Write(buffer, 0, size);
} while (size > 0);
zipOutStream.Close();
fileStreamOut.Close();
fileStreamIn.Close();
}
View Code
(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 />;
size = zipInStream.Read(buffer, 0, buffer.Length);
fileStreamOut.Write(buffer, 0, size);
} while (size > 0);
zipInStream.Close();
fileStreamOut.Close();
fileStreamIn.Close();
}
View Code
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");
}
View Code
(2)解压
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];
size = zipInStream.Read(buffer, 0, buffer.Length);
fileStreamOut.Write(buffer, 0, size);
} while (size > 0);
zipInStream.Close();
fileStreamOut.Close();
fileStreamIn.Close();
}
View Code
三、在.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);
}
View Code
有错误的请多多指教,共同进步(๑•ᴗ•๑)
By听雨的人