.net压缩文件夹

1,引用:using System.IO.Packaging;

2,压缩文件的方法:

/// <summary>
/// 压缩文件夹到制定的路径
/// </summary>
/// <param name="folderName">要压缩的文件物理路径</param>
/// <param name="compressedFileName">目标文件物理路径和文件名</param>
/// <param name="overrideExisting">是否覆盖存在的文件</param>
/// <returns></returns>
static bool PackageFolder(string folderName, string compressedFileName, bool overrideExisting)
{
if (folderName.EndsWith(@"\"))
folderName = folderName.Remove(folderName.Length - );
bool result = false;
if (!Directory.Exists(folderName))
{
return result;
} if (!overrideExisting && File.Exists(compressedFileName))
{
return result;
}
try
{
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;
}
上一篇:DataTable中执行DataTable.Select("条件"),


下一篇:DevGridControl中GridView排序问题