.net压缩文件夹

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

2,压缩文件的方法:

/// 
    /// 压缩文件夹到制定的路径
    /// 
    /// 要压缩的文件物理路径
    /// 目标文件物理路径和文件名
    /// 是否覆盖存在的文件
    /// 
    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;
        }
        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;
    }

 

你可能感兴趣的:(.net压缩文件夹)