正在将 PCL 中的文件夹压缩为 gzip/zip 文件

Compressing a folder to gzip/zip file from PCL

我在同一解决方案中开发 UWP 和 Windows phone 8.1。

在这两个项目中,我都需要将整个文件夹压缩成一个 gzip 文件的功能(以便将其发送到服务器)。

我尝试过并遇到问题的库:

SharpZipLib - 使用 System.IClonable 我无法在我的 PCL 项目中引用

DotNetZip - 不支持 PCL/UWP

System.IO.Compression - 只能使用 Stream,不能压缩整个文件夹

我可以拆分每个平台的实现(虽然它并不完美)但我仍然没有找到可以在 UWP 中使用的东西。

如有帮助,我们将不胜感激

在 UWP 库上工作,您将不得不使用 System.IO.Compression 的 Stream 子系统。当您需要 PCL 版本的 .NET Framework 时,有很多这样的限制。接受它。

在您的上下文中,这不是什么大问题。

要求的用法是:

using System;
using System.IO;
using System.IO.Compression;

然后方法...

    private void CreateArchive(string iArchiveRoot)
    {
        using (MemoryStream outputStream = new MemoryStream())
        {
            using (ZipArchive archive = new ZipArchive(outputStream, ZipArchiveMode.Create, true))
            {
                //Pick all the files you need in the archive.
                string[] files = Directory.GetFiles(iArchiveRoot, "*", SearchOption.AllDirectories);

                foreach (string filePath in files)
                {
                    FileAppend(iArchiveRoot, filePath, archive);
                }
            }
        }
    }

    private void FileAppend(
        string iArchiveRootPath,
        string iFileAbsolutePath,
        ZipArchive iArchive)
    {
        //Has to return something like "dir1/dir2/part1.txt".
        string fileRelativePath = MakeRelativePath(iFileAbsolutePath, iArchiveRootPath);

        ZipArchiveEntry clsEntry = iArchive.CreateEntry(fileRelativePath, CompressionLevel.Optimal);
        Stream entryData = clsEntry.Open();

        //Write the file data to the ZipArchiveEntry.
        entryData.Write(...);
    }

    //
    private string MakeRelativePath(
        string fromPath, 
        string toPath)
    {
        if (String.IsNullOrEmpty(fromPath)) throw new ArgumentNullException("fromPath");
        if (String.IsNullOrEmpty(toPath))   throw new ArgumentNullException("toPath");

        Uri fromUri = new Uri(fromPath);
        Uri toUri = new Uri(toPath);

        if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.

        Uri relativeUri = fromUri.MakeRelativeUri(toUri);
        String relativePath = Uri.UnescapeDataString(relativeUri.ToString());

        if (toUri.Scheme.Equals("file", StringComparison.OrdinalIgnoreCase))
        {
            relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
        }

        return relativePath;
    }

好的,所以我找到了这个名为 SharpZipLib.Portable 的项目,它也是一个开源项目 Github : https://github.com/ygrenier/SharpZipLib.Portable

真不错:)