2

我对 WinRT 开发平台有点陌生,它已经让我发疯了(我是一名长期的 .Net 开发人员,所有那些被删除的 API 都很烦人)我在压缩所有文件时遇到问题Windows.Storage.ApplicationData.Current.TemporaryFolder 这是我当前的代码(VB.Net,基于 MSDN 代码,“文件”是我将所有文件放入的 zip 文件):

Using zipMemoryStream As New MemoryStream()
Using zipArchive As New Compression.ZipArchive(zipMemoryStream, Compression.ZipArchiveMode.Create)
    For Each fileToCompress As Windows.Storage.StorageFile In (Await Windows.Storage.ApplicationData.Current.TemporaryFolder.GetFilesAsync())
        Dim buffer As Byte() = WindowsRuntimeBufferExtensions.ToArray(Await Windows.Storage.FileIO.ReadBufferAsync(fileToCompress))
        Dim entry As ZipArchiveEntry = zipArchive.CreateEntry(fileToCompress.Name)
        Using entryStream As Stream = entry.Open()
            Await entryStream.WriteAsync(buffer, 0, buffer.Length)
        End Using
    Next
End Using
Using zipStream As Windows.Storage.Streams.IRandomAccessStream = Await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)
    Using outstream As Stream = zipStream.AsStreamForWrite()
        Dim buffer As Byte() = zipMemoryStream.ToArray()
        outstream.Write(buffer, 0, buffer.Length)
        outstream.Flush()
    End Using
End Using
End Using

它构建得很好,但是当我启动代码时,出现异常:UnauthorizedAccessException:访问被拒绝。(HRESULT 异常:0x80070005 (E_ACCESSDENIED))在线:WindowsRuntimeBufferExtensions.ToArray(blahblah... 我想知道怎么了。知道吗?

提前致谢 !

4

1 回答 1

1

我用 C# 重写了你的方法来尝试一下:

var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("test.zip");

using (var zipMemoryStream = new MemoryStream())
{
    using (var zipArchive = new System.IO.Compression.ZipArchive(zipMemoryStream, System.IO.Compression.ZipArchiveMode.Create))
    {
        foreach (var fileToCompress in (await ApplicationData.Current.TemporaryFolder.GetFilesAsync()))
        {
            var buffer = WindowsRuntimeBufferExtensions.ToArray(await FileIO.ReadBufferAsync(fileToCompress));
            var entry = zipArchive.CreateEntry(fileToCompress.Name);
            using (var entryStream = entry.Open())
            {
                await entryStream.WriteAsync(buffer, 0, buffer.Length);
            }
        }
    }

    using ( var zipStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
    {
        using (var outstream = zipStream.AsStreamForWrite())
        {
            var buffer = zipMemoryStream.ToArray();
            outstream.Write(buffer, 0, buffer.Length);
            outstream.Flush();
        }
    }
}

它完美地工作 - 它按预期在本地文件夹中创建 zip 文件。由于您在调用中遇到异常ToArray,原因可能是您尝试打开的文件已经从其他地方锁定。如果您自己创建这些文件,或者只是访问它们,请确保您关闭了流。

要测试此方法,您可以在 temp 文件夹中手动创建一个文件夹,将几个文件放入其中,然后在该文件夹(文件位于C:\Users\<Username>\AppData\Local\Packages\<PackageName>\TempState)上运行该方法,以排除任何其他错误原因。

于 2012-11-28T06:04:00.827 回答