【问题标题】:File.ReadAllBytes throwing UnauthorizedAccessException: 'Access to the path is denied' UWPFile.ReadAllBytes throwing UnauthorizedAccessException: 'Access to the path is denied' UWP
【发布时间】:2019-12-29 14:42:16
【问题描述】:

我正在创建一个 UWP 应用程序,并且我正在尝试将图像从文件读取到字节 []。我不知道为什么,但我总是从任何文件路径中获取异常...我尝试从不同的项目运行相同的方法 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 中使用此示例代码,但它不起作用。代码在微软文档页面中。

【问题讨论】:

标签: c# uwp


【解决方案1】:

与其直接通过路径访问文件,不如在UWP中使用FileOpenPicker打开文件。

您可以使用此代码:

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

最好的问候。

【讨论】:

  • 你能更好地解释一下这段代码是如何工作的吗?我是 uwp 的初学者,在此先感谢
  • OpenLocalFile方法中,params string[]表示可以传递多个字符串参数或字符串数​​组,这对于需要打开多种格式的应用很有用。传入参数后,我们需要验证参数是否符合文件扩展名格式(如.jpg.png)。之后,我们使用FileOpenPicker 进行文件选择。如果你想了解更多,请参考这个document
猜你喜欢
  • 2020-11-15
  • 2019-02-20
  • 1970-01-01
  • 2018-03-06
  • 1970-01-01
  • 2020-04-26
  • 2022-12-27
  • 2022-12-01
  • 1970-01-01
相关资源
最近更新 更多