为什么我无法从我的 Xamarin.Forms UWP 应用程序访问 DownloadsFolder,获得 System.UnauthorizedAccessException?

Why can’t I access the DownloadsFolder from my Xamarin.Forms UWP application, getting a System.UnauthorizedAccessException?

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

Access to the path 'C:\Users\tikoz\Downloadsb8dad0-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 指令引发的上述异常。是我误解了文档,还是漏掉了什么?

I want to download files saved in Azure File Shares. The catch clause catches the exception mentioned above, raised by the File.OpenWrite(checkAlreadyExistingFile.Path instruction.

请在此处勾选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.
}