1

I am pretty stuck with Xamarin.Forms/Android at the moment, I need to download a csv file from a specific URL in the 'Download' directory of my phone, however I continuously get System.UnauthorizedAccessException: Access to the path "/storage/emulated/0/Download/myFile.csv" is denied.

public async Task DownloadAsync(string url)
    {
        try
        {
            using(var webClient = new WebClient())
            {
                var directoryPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
                string pathToNewFile = Path.Combine(directoryPath, myFile.csv);

                await webClient.DownloadFileTaskAsync(new Uri(url), pathToNewFile);
            }
        }
        catch(Exception ex)
        {
            throw;
        }
    }`

These are my permissions setup:

  • INTERNET
  • WRITE_EXTERNAL_STORAGE
  • ACCESS_COARSE_LOCATION
  • ACCESS_FINE_LOCATION
  • READ_EXTERNAL_STORAGE

I cannot get it why it does not work. By the way I am testing on a physical device(Pixel3), maybe I shall set some configuration inside my phone... have no idea what's wrong here

Denis
  • 163
  • 1
  • 11
  • you can't just write to the device's Downloads folder - you need to use DownloadManager – Jason Sep 17 '19 at 21:25
  • I don't understand why do I need a DownloadManager, shall not my application act like one, basically every file type represents some chunks of bytes, I cannot transfer these bytes on my phone? a bit confused – Denis Sep 17 '19 at 21:35
  • because your app is not allowed to write directly to the system Downloads folder. You need to use the Android DownloadManager API if you want to do that. There are other user writable folders available that would work, but Downloads is not one of them. – Jason Sep 17 '19 at 21:39
  • 1
    @Denis You need to request "Runtime permission" to external storage and the user must accept, then you can save your file: https://stackoverflow.com/a/48168838/4984832 – SushiHangover Sep 17 '19 at 21:46

1 Answers1

1

Your code will not work on API level 23 or higher.

You have to ask for the permission at the runtime. Here's the post on that: https://devblogs.microsoft.com/xamarin/requesting-runtime-permissions-in-android-marshmallow/

Ivan Ičin
  • 9,672
  • 5
  • 36
  • 57