2016-05-16 44 views
1

我在同一解决方案中开发UWP和Windows Phone 8.1。从PCL压缩gzip/zip文件的文件夹

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

图书馆我已经试过与遇到的问题:

SharpZipLib - 不Suporting PCL/UWP

- 使用System.IClonable我不能在我的PCL项目

DotNetZip全球化志愿服务青年

System.IO.Compression - 仅与Stream一起工作,无法压缩整个文件夹

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

任何帮助将appriciated

+0

你能解释一下吗?详细介绍,为什么你不能使用IO.Compression?我从来没有在ZipFile库中使用CreateFromDirectory的问题,但我也没有编写UWP或WP应用程序,所以也许是这个问题? – gravity

+0

哦,必须错过CreateFromDirectory :)我会尝试 –

+0

Apperenlty我只是没有ZipFile在IO.Compression命名空间,我有:ZipArchive,GZipStream,DeflateStream - 它们都只能用于Stream ... –

回答

-1

在UWP库,你将不得不使用System.IO.Compression的流子系统工作。当您需要.NET Framework的PCL版本时,有许多这样的限制。住在那。

在你的情况下,这不是一个麻烦。

所需usings是:

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(...); 
    } 

    //http://stackoverflow.com/questions/275689/how-to-get-relative-path-from-absolute-path 
    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; 
    } 
+0

我试过使用类似的东西,但它并没有给我创建一个常规的gzip文件(我可以在Linux服务器上例如uzip)。你有没有设法创建一个gzip格式的文件,该文件将作为一个文件夹与您添加到Stream(clsEntry)的文件一起解压缩? –

+0

我能够重新编译DotNetZip(https://dotnetzip.codeplex.com/)作为Windows 8.1/Windows Phone 8.1的PCL,没有大问题,花了大约一个小时,但还没有尝试过。我必须做的大部分工作是替换文件系统调用。 –