Xamarin : Android : System.UnauthorizedAccessException: Access to the path is denied
Solution 1
Ok I Fixed it by changing the saving location to System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)
Don't ask me why that worked when they need the same permissions but it did.
Solution 2
First of all add this permissions to you Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Since Android 6.0 (API 23) you need also to request the permissions manually, add this code on your MainActivity.cs on your Xamarin.Android project:
if ((ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)
|| (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted))
{
ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage }, REQUEST);
}
Since Android 10 you may also need to add android:requestLegacyExternalStorage
attribute to your Manifest like this:
<application android:requestLegacyExternalStorage="true" />
UPDATE
After doing all this maybe you still get the exception on Android 11 or greather If you try save a file on any path of the SDCARD, you can only use the EXTERNAL STORAGE and INTERNAL STORAGE paths of your App by default.
PRIVATE EXTERNAL STORAGE PATH OF YOUR APP:
Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath
PRIVATE INTERNAL STORAGE PATH OF YOUR APP:
System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData)
If you need to access to any path of the SDCARD on Android 11 or greather, you should ask for manage all files access permission.
private void RequestStorageAccess()
{
if (!Environment.IsExternalStorageManager)
{
StartActivityForResult(new Intent(Android.Provider.Settings.ActionManageAllFilesAccessPermission), 3);
}
}
This will pop up an Activity listing all the Apps that have access to all file access permission, the user should tap your App and enable the permission.
But in order to make your App appear there, you should add this permission to your manifest:
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
And you also need to make sure that you are compiling your App with Android 11 or greather.
Here you can see the permission Activity:
For some reason I was able to save files to documents folder without this permission, but after deleting the files I was not able to create again the same files with the same name, also I was not able to list all the files, this is why this pop-up is needed even to use the documents directory.
Use manage all files permission only in case that you really need
If you want to publish your App in Google Play with the "Manage All Files Permission", you will have to Fill a "Permissions Declaration Form" on Google Play, because it is considered a "high-risk or sensitive permissions" here is more information, and Google should approve it:
https://support.google.com/googleplay/android-developer/answer/9214102?hl=en#zippy=
When to ask for this permission:
https://support.google.com/googleplay/android-developer/answer/10467955?hl=en
Solution 3
Xamarin.Forms (Android solution)
MainActivity.cs
- For apps that target Android 5.1(API level 22) or lower, there is nothing more that needs to be done.
- Apps that will run on Android 6.0(API 23 level 23) or higher should ask Run time permission checks.
protected override void OnCreate(Bundle bundle)
{
if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
{
if (!(CheckPermissionGranted(Manifest.Permission.ReadExternalStorage) && !CheckPermissionGranted(Manifest.Permission.WriteExternalStorage)))
{
RequestPermission();
}
}
LoadApplication(new App());
}
private void RequestPermission()
{
ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage }, 0);
}
public bool CheckPermissionGranted(string Permissions)
{
// Check if the permission is already available.
if (ActivityCompat.CheckSelfPermission(this, Permissions) != Permission.Granted)
{
return false;
}
else
{
return true;
}
}
Euan Hollidge
I'm just here to code :P I know java and c# (both self taught so no where near perfect) and mess around in html from time to time.
Updated on July 09, 2022Comments
-
Euan Hollidge almost 2 years
So I'm trying to create a file and I'm getting System.UnauthorizedAccessException: Access to the path "/DownloadJitters" is denied. I'm not sure if it's a permissions thing (I've tried a write to external storage in case but that didn't work) or something else. Also I'm trying to figure out a good place to write these files as I would like them not to be easily found. Any ideas? Here's the code as well :
public void favouriteList(MainActivity av, Ordering o, string favouriteName, string totalCost, JittersListView jlv) { //Checks Directory exists if (File.Exists(Android.OS.Environment.DirectoryDownloads + "/Jitters/FavouritesListAdded.txt") == false) { Directory.CreateDirectory(Android.OS.Environment.DirectoryDownloads + "Jitters/FavouriteList/"); File.Create(Android.OS.Environment.DirectoryDownloads + "/Jitters/FavouritesListAdded.txt"); } if (File.Exists(Android.OS.Environment.DirectoryDownloads + "Jitters/FavouriteList/" + favouriteName + ".txt") == false) { var fav = File.Create(Android.OS.Environment.DirectoryDownloads + "Jitters/FavouriteList/" + favouriteName + ".txt"); fav.Close(); string file = Android.OS.Environment.DirectoryDownloads + "Jitters/FavouriteList/" + favouriteName + ".txt"; string added = null; int current = 0; while (true) { if (current < jlv.Count) { JittersListItem jli = jlv[current]; added += jli.Top + "|" + jli.Bottom + "|" + jli.itemPic + "|" + jli.itemDes + System.Environment.NewLine; current++; } else { break; } } File.AppendAllText(file, favouriteName + "|" + totalCost + added); } else { new AlertDialog.Builder(av) .SetMessage("Please use a different name, this one has been taken.") .Show(); } }
-
Euan Hollidge over 8 yearsok I added in the slashes and the error still occurs :/ except instead of "/DownloadJitters" its just "/Download"
-
Euan Hollidge over 8 yearsCorrected the comment above same error but with "/Download" as the path
-
Steven Mark Ford almost 8 yearsI got this error when saving with an Title case file name. when I changed to all lower case it worked. some bug.
-
Harish Patil about 2 yearsThis should be marked as perfect answer, as other answers lead me towards few more errors related to fast deploymnet. Thanks Divyesh_08 worked for me.
-
Harish Patil about 2 yearsThis actually lead me to a unfortunate debug & fast deployment issue. This issue came when manifest file edited with <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> & related lines.