Access to the path is denied xamarin forms

Prashant Sharma 66 Reputation points
2021-06-28T12:17:26.35+00:00

I am trying to copy my db file to internal storage root/document. My codes are working good till Android 9 but after it i am getting the error "System.UnauthorizedAccessException: Access to the path "/storage/emulated/0/Documents/FruitsApp/Backup/Fruits.db_2021-06-28 12:20:20" is denied" I have try lots of way to copy all are working before Android 9 but after it i am getting above error. I am sharing my all codes. Thanks in advance.

Java.IO.File mediaStorageDir = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments) + path);            

            if (!mediaStorageDir.Exists())
            {
                var tt = mediaStorageDir.Mkdirs();

                if (mediaStorageDir.Mkdirs() == false)
                {

                    var fail = "failed to create";

                }
            }


            var directoryPath = mediaStorageDir.AbsolutePath;


          ////////--this way to create folder is working till andorid 9

           //var PathExists = Directory.Exists(directoryPath);

            //if (PathExists ==false)
            //{
            //    Directory.CreateDirectory(directoryPath);
            //}


            var dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "Fruits.db");


            FileInfo file = new FileInfo(dbPath);

            var dbName = file.Name;

            var fullFileName = string.Concat("/", dbName + "_", Global.CurrentDateTime());

            var newpath = string.Format("{0}{1}", directoryPath, fullFileName);

              //////--- First way copy file from source to destination is working tille android 9

            //using (FileStream sourceStream = System.IO.File.Open(dbPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            //using (FileStream destinationStream = System.IO.File.Create(newpath))
            //{
            //     sourceStream.CopyToAsync(destinationStream);
            //}

         //////--- 2nd way copy file from source to destination is working tille android 9

            byte[] dbFile = System.IO.File.ReadAllBytes(dbPath);
            System.IO.File.WriteAllBytes(newpath, dbFile);


            //////--- 3rd way copy file from source to destination is working tille android 9
            //file.CopyTo(newpath);

I have try 3 ways to copy file from source to another all ways are working till android 9 but not working after android 9.

--Android Manifest file

<?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" 
    android:versionName="1.0" package="com.NewWave.FruitApp" android:installLocation="auto">
   <uses-sdk android:minSdkVersion="23" android:targetSdkVersion="30" />
   <application android:requestLegacyExternalStorage="true" android:label="FruitApp" 
   android:theme="@style/MainTheme"></application>
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
   <uses-permission android:name="android.permission.CALL_PHONE" />
   <uses-permission android:name="android.permission.SEND_SMS" />
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" 
   android:maxSdkVersion="29" />
    <uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />
    <!--<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />-->
    </manifest>
Developer technologies .NET Xamarin
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2021-06-29T02:48:03.74+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments) is deprecated, And We no longer have access to create a directory on Android 10+ in the public external storage, here is simlar thread, you can refer to it.
    https://stackoverflow.com/a/58379655/8354952

    I recommend you to use following path, you can store DB files into your own application's external storage (here is path :"/storage/emulated/0/Android/data/com.companyname.rrecordaudiopermission1/filesfilename.png")

       string testPath= Android.App.Application.Context.GetExternalFilesDir("").AbsolutePath + $"{filename}.png";  
    

    110044-image.png

    ===================
    Update=========================

    If you user could grand the android.permission.MANAGE_EXTERNAL_STORAGE, you can create a folder in the android 11.

    First of all, add this permission in your AndroidManifest.xml.

       <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />  
    

    Then, use Snackbar to grand the permission.

       if (!Environment.IsExternalStorageManager)  
                   {  
                       Snackbar.Make(FindViewById(Android.Resource.Id.Content), "Permission needed!", Snackbar.LengthIndefinite)  
                               .SetAction("Settings", new MyOnClickListener(this)).Show();  
                   }  
         
         
         
         internal class MyOnClickListener:Java.Lang.Object,View.IOnClickListener  
           {  
               private MainActivity mainActivity;  
         
               public MyOnClickListener()  
               {  
               }  
         
               public MyOnClickListener(MainActivity mainActivity)  
               {  
                   this.mainActivity = mainActivity;  
               }  
         
               public void OnClick(View v)  
               {  
                   // throw new System.NotImplementedException();ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION  
         
                   try  
                   {  
                       mainActivity.StartActivity(new Intent(  
           Android.Provider.Settings.ActionManageAllFilesAccessPermission,  
           Android.Net.Uri.Parse("package:" + Android.App.Application.Context.PackageName)));  
                        
                   }  
                   catch (Exception ex)  
                   {  
                       Intent intent = new Intent();  
                       intent.SetAction(Android.Provider.Settings.ActionManageAllFilesAccessPermission);  
                       mainActivity.StartActivity(intent);  
                   }  
               }  
           }  
       }  
    

    If you user grand this permission, you can create folder like following screenshot.

    110231-image.png

    Best Regards,

    Leon Lu


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Prashant Sharma 66 Reputation points
    2021-07-02T18:20:59.267+00:00

    Thank u very much sir for your guidance . My all errors has been solved on my app.

    1. the format for backup with date and time i was taking that was the man problem.
    2. after the permission for all files and folder my main problem of creating the file and folder has been solved.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.