首页 > 解决方案 > 为什么我无法从我的 Xamarin.Forms UWP 应用程序访问 DownloadsFolder,并获得 System.UnauthorizedAccessException?

问题描述

我的 Xamarin.Forms UWP 应用程序需要将文件保存在用户设备上。文档说 UWP 应用程序可以访问在通常的“下载”文件夹中创建的相应文件夹。但是,当我尝试使用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我是否误解了文档,或者我错过了什么?

标签: c#xamarinxamarin.formsuwpxamarin.uwp

解决方案


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

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

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

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

推荐阅读