question

PrashantSharma-9315 avatar image
0 Votes"
PrashantSharma-9315 asked RobCaplan edited

Access to the path is denied xamarin forms

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>
dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

LeonLu-MSFT avatar image
0 Votes"
LeonLu-MSFT answered PrashantSharma-9315 edited

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.



image.png (46.2 KiB)
image.png (38.1 KiB)
· 12
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@LeonLu-MSFT Sir want to use the external device folder for my backup and other files by that if user unstall the app then data will be remain in download or document folder.
I am able to create the folder in download or document folders also i can create a text file and open or edit or pass text in android 10 and 11 .
But my problem is to copy my db file from app folder to download or document folder on that i am getting error of "Acess path denied". If this is totally not possible then whatsapp is also doing same thing. I don't know how whatsapp do this . Kindly guide me in this

0 Votes 0 ·

Please see my updated answer.

0 Votes 0 ·

@LeonLu-MSFT Sir thank u for this solution and i have given all permission to the app also wrote this code to my manifest file "android:requestLegacyExternalStorage="true""
I can create folder but still my problem is remain that i want to copy my db file from app folder to a external folder which is giving me error

0 Votes 0 ·
Show more comments
PrashantSharma-9315 avatar image
0 Votes"
PrashantSharma-9315 answered

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.