简体   繁体   English

Zipfile OpenRead 在 c# uwp 应用程序中抛出对路径的访问被拒绝异常?

[英]Zipfile OpenRead throws Access to the path is denied exception in c# uwp app?

I've been using the following piece of code for months without a problem and all of a sudden, it throws at me the "Access to the path is denied" exception.几个月来我一直在毫无问题地使用以下代码,但突然间,它向我抛出“访问路径被拒绝”异常。 I've been using "BroadFileSystemAccess" in my manifest and am using a file picker to pick the file I'm passing as StorageFile parameter.我一直在我的清单中使用“BroadFileSystemAccess”,并使用文件选择器来选择我作为 StorageFile 参数传递的文件。 I also made sure the application has FileAccess enabled.我还确保应用程序启用了 FileAccess。

What's wrong?怎么了? Can't figure it out after hours of debugging and searching...经过数小时的调试和搜索无法弄清楚......

public async Task AddImageToPlaylist(StorageFile NewImage)
{

        try {
            using (ZipArchive archive = ZipFile.OpenRead(NewImage.Path))
            {
                foreach (ZipArchiveEntry member in archive.Entries)
                {
                    NumSlides += 1;
                    AllFiles.Add(new imgitem { type = "zip", zipname = NewImage.Path, filepath = member.FullName, imgname = NewImage.Name, imgsize = (ulong)member.Length, imgdate = member.LastWriteTime, index = NumSlides, ImgRating = 0 });
                 }
                    
            }
            
        }
        catch (Exception)
        {
            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { MessageBlock.Text = "Exception encountered loading ZIP file"; });
        }
        
}

Stream your StorageFile into a ZipArchive rather than discarding the StorageFile and reopening the file from its path with ZipFile.Open. Stream 将您的 StorageFile 放入 ZipArchive,而不是丢弃 StorageFile 并使用 ZipFile.Open 从其路径重新打开文件。 Something like the following:类似于以下内容:

using System.IO;
....
ZipArchive archive = new ZipArchive(await NewImage.OpenStreamForReadAsync());

BroadFileSystemAccess gives access only via the Windows.Storage classes - see Accessing additional locations . BroadFileSystemAccess 仅通过 Windows.Storage 类提供访问权限 - 请参阅访问其他位置 ZipFile.OpenRead() tries to reopen the path directly using System.IO instead of Windows.Storage. ZipFile.OpenRead() 尝试使用 System.IO 而不是 Windows.Storage 直接重新打开路径。 This will fail unless the path is in a location (eg application data) that the app can read without added permissions.除非路径位于应用程序无需添加权限即可读取的位置(例如应用程序数据),否则这将失败。

For reading and writing file your application should have Administrative permissions in aap.manifest对于读取和写入文件,您的应用程序应在 aap.manifest 中具有管理权限

<security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!-- UAC Manifest Options
             If you want to change the Windows User Account Control level replace the 
             requestedExecutionLevel node with one of the following.

        <requestedExecutionLevel  level="asInvoker" uiAccess="false" />
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
        <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />

            Specifying requestedExecutionLevel element will disable file and registry virtualization. 
            Remove this element if your application requires this virtualization for backwards
            compatibility.
        -->
        <requestedExecutionLevel level="requireAdministrator" uiAccess="true" />
      </requestedPrivileges>
      <applicationRequestMinimum>
        <defaultAssemblyRequest permissionSetReference="Custom" />
        <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true" ID="Custom" SameSite="site" />
      </applicationRequestMinimum>
    </security>

I am using the same code as Francois but was making two passes through the zip file similar to the code below.我使用与 Francois 相同的代码,但两次通过 zip 文件,类似于下面的代码。 The second time would randomly get this error.第二次会随机得到这个错误。 I finally figured out how to do the work with one loop and it works well now.我终于想出了如何用一个循环完成这项工作,现在效果很好。 BTW, I tried everything including putting a Sleep(1000) and even a user prompt between the loops and nothing made any difference.顺便说一句,我尝试了所有方法,包括在循环之间放置 Sleep(1000) 甚至用户提示,但没有任何区别。 As is so often the case, problems like this are sometimes indicators of structural problems and the solution can result in cleaner code, ie one loop instead of two.通常情况下,像这样的问题有时是结构问题的指标,解决方案可以产生更清晰的代码,即一个循环而不是两个。

            try {
                using (ZipArchive archive = ZipFile.OpenRead(NewImage.Path))
                {
                    foreach (ZipArchiveEntry member in archive.Entries)
                    {
                        // do some preprocessing here
                    }
                }
                using (ZipArchive archive = ZipFile.OpenRead(NewImage.Path))
                {
                    foreach (ZipArchiveEntry member in archive.Entries)
                    {
                        // do final processing here
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"{e.Message}");
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM