'Could not load file or assembly System.IO.Compression' 是 UWP

'Could not load file or assembly System.IO.Compression' on UWP

我的应用程序是一个通用 Window 平台应用程序。我尝试实现一个运行时组件来解压缩压缩文件夹。我的要求之一是可以处理超过 260 个字符的路径。

public static IAsyncActionWithProgress < string > Unzip(string zipPath, string destination) {
    return AsyncInfo.Run < string > (async(_, progress) => {
        var zipFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(zipPath));

        try {
            Stream stream = await zipFile.OpenStreamForReadAsync();
            ZipArchive archive = new ZipArchive(stream);
            archive.ExtractToDirectory(destination);
        } catch (Exception e) {
            Debug.WriteLine(e.Message);
        }
    });
}

我尝试执行我的方法并收到以下异常消息:

System.IO.FileNotFoundException: Could not load file or assembly 'System.IO.Compression, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified.
   at Zip.Zip.<>c__DisplayClass0_0.<<Unzip>b__0>d.MoveNext()
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
   at Zip.Zip.<>c__DisplayClass0_0.<Unzip>b__0(CancellationToken _, IProgress`1 progress)
   at System.Thread (~4340)

我尝试使用 NuGet 添加 System.IO.Compression,但我仍然遇到相同的错误。 zip 文件和目标文件夹存在。

我尝试在 Visual Studio 2015 而不是 Visual Studio 2017 调试我的项目,发现我可以用那种方式使用 System.IO.Compression 但有长度限制路径。

首先,通过我这边的测试,使用最新的 Visual Studio 2017,默认情况下,您的代码片段可以很好地处理少于 260 个字符的文件路径。如果使用超过 260 个字符的路径 visual studio 2017 将抛出异常

System.IO.PathTooLongException: 'The filename or extension is too long.

与 Visual Studio 2015 相同。所以请检查您是否正确使用了命名空间。 using System.IO.Compression;

One of my requirements is that paths which are longer than 260 characters can be handled.

其次,当您尝试通过GetFileFromApplicationUriAsync 方法获取文件时抛出错误。所以这不是System.IO.Compression命名空间的问题,你真正需要解决的是最大路径长度限制,详情请参考this article. For more details about file path too long issue please try to reference this thread。但它们可能不适合 UWP 应用程序。

在 UWP 应用程序中,您可以使用 FileOpenPicker 获取文件并将文件传递给组件以读取文件流。文件选择器会将长文件名转换为像"xxx-UN~1.ZIP"这样的截图供阅读。

FileOpenPicker openpicker = new FileOpenPicker();
openpicker.FileTypeFilter.Add(".zip");
var zipfile = await openpicker.PickSingleFileAsync();
Stream stream = await zipfile.OpenStreamForReadAsync();
ZipArchive archive = new ZipArchive(stream);
archive.ExtractToDirectory(destination);

我建议您避免使用长文件路径。