微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我无法从 Xamarin.Forms UWP 应用程序访问 DownloadsFolder,并收到 System.UnauthorizedAccessException?

如何解决为什么我无法从 Xamarin.Forms UWP 应用程序访问 DownloadsFolder,并收到 System.UnauthorizedAccessException?

我的 Xamarin.Forms UWP 应用程序需要在用户设备上保存文件docs 表示应用程序可以访问在通常的“下载”文件夹中创建的适当文件夹。但是,当我尝试使用 DownloadsFolder 类在那里保存文件时,出现以下异常:

Access to the path 'C:\Users\tikoz\Downloads\38b8dad0-9c00-4b76-8f23-59192c50b740_enn3pya30cxd2!App\tff20210219204840.jpg' is denied.

我用来下载文件代码如下:

try {
   var checkAlreadyExistingFile = await Windows.Storage.DownloadsFolder.CreateFileAsync(fileName,CreationCollisionoption.FailIfExists);

   var share = new ShareClient(StorageAccountConnectionString,FileShareName);
   var directory = share.GetDirectoryClient(string.Empty);
   var file = directory.GetFileClient(fileName);

   ShareFileDownloadInfo download = await file.DownloadAsync();
   using (var stream = File.OpenWrite(checkAlreadyExistingFile.Path)) { // Raises the exception
      await download.Content.copyToAsync(stream);
      DownloadedReceiptimagePath = stream.Name;
      return DownloadedReceiptimagePath;
   }
}
catch (Exception e) {
   Console.WriteLine(e);
   return null;
}

我想下载保存在 Azure 文件共享中的文件catch 子句捕获上述异常,由 File.OpenWrite(checkAlreadyExistingFile.Path 指令引发。我是误解了文档,还是遗漏了什么?

解决方法

我想下载保存在 Azure 文件共享中的文件。 catch 子句捕获上述由 File.OpenWrite(checkAlreadyExistingFile.Path 指令引发的异常。

请在此处查看 DownloadsFolder document。创建或访问下载文件夹中的文件不需要功能。但是您需要使用 Windows Storage Api 而不是 System.IO(OpenWrite)。你可以像下面这样写作。

var checkAlreadyExistingFile = await Windows.Storage.DownloadsFolder.CreateFileAsync("Test",CreationCollisionOption.FailIfExists);

using (var stream = await checkAlreadyExistingFile.OpenStreamForWriteAsync())
{ 
    // process stream here.
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。