抛出UnauthorizedAccessException的File.ReadAllBytes:“拒绝访问路径” UWP

时间:2019-12-29 14:42:16

标签: c# uwp

我正在创建UWP应用,并且试图将图像从文件读取到Byte []。我不知道为什么,但是我总是从任何文件路径中获取异常...我尝试从另一个项目中运行相同的方法File.ReadAllBytes,并且没有引发异常。这是我项目中的权限问题吗?

Foto = File.ReadAllBytes(@"C:\users\migue\Desktop\aladin.jpg");
<Package
  ...
  xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
  IgnorableNamespaces="uap mp uap5 rescap">
...
<Capabilities>
    <rescap:Capability Name="broadFileSystemAccess" />
</Capabilities>

我尝试在appmanifest中使用此示例代码,但是它不起作用。该代码在Microsoft文档页面中。

2 个答案:

答案 0 :(得分:1)

建议不要使用路径直接访问文件,而建议使用FileOpenPicker在UWP中打开文件。

您可以使用以下代码:

public async static Task<StorageFile> OpenLocalFile(params string[] types)
{
    var picker = new FileOpenPicker();
    picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
    Regex typeReg = new Regex(@"^\.[a-zA-Z0-9]+$");
    foreach (var type in types)
    {
        if (type == "*" || typeReg.IsMatch(type))
            picker.FileTypeFilter.Add(type);
        else
            throw new InvalidCastException("File extension is incorrect");
    }
    var file = await picker.PickSingleFileAsync();
    if (file != null)
        return file;
    else
        return null;
}

用法

var file = await OpenLocalFile(".jpg");
var bytes = (await FileIO.ReadBufferAsync(file)).ToArray();

最诚挚的问候。

答案 1 :(得分:-1)

以管理员模式打开Visual Studio,然后重试。如果仍然无法解决问题,则只需将其保存在C以外的驱动器中即可。

相关问题