0

My Xamarin.Forms UWP application needs to save files on the user’s device. The docs says a UWP the application can access the appropriate folder created inside the usual “Downloads” folder. However, when I try to save a file there using the DownloadsFolder class, I get the following exception:

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

The code I use to download a file is the following:

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;
}

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. Do I misunderstand the docs, or do I miss something?

Pine Code
  • 2,466
  • 3
  • 18
  • 43

1 Answers1

0

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.

Please check DownloadsFolder document here. Capabilities are not needed to create or access files in the Downloads folder. But you need use Windows Storage Api but not System.IO(OpenWrite). You could get steam for writing like the following.

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

using (var stream = await checkAlreadyExistingFile.OpenStreamForWriteAsync())
{ 
    // process stream here.
}
Nico Zhu
  • 32,367
  • 2
  • 15
  • 36