[FIXED] Android.OS.Environment.GetExternalStoragePublicDirectory is deprecated. Alternative?

Issue

I’m currently building a .Net Maui App that is only targeting android. I need to save some data in the public external storage that I can access and copy to my PC and that persists even if I uninstall the app. I choose the Documents directory.

The following does the job:

string dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).AbsolutePath

But I get a warning from my IDE that GetExternalStoragePublicDirectory is deprecated.

I’ve found several postings that

Android.App.Application.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryDocuments)

will also work, but that does not return the same result.
The deprecated method returns

/storage/emulated/0/Documents

while the other one returns

/storage/emulated/0/Android/data/com.companyname.myappname/files/Documents

Hence the appname is in the path, this is not persistent in case the app is uninstalled. So what is the correct way to get the public external documents directory?

Solution

I had done a sample to test the MediaStore and the Context api. According to your description, you want to save some data to the file in the Document folder.

For the Context

All the files or directories you get from it belong to the application, when user uninstall the app from the devices, all of these will be deleted from the device. So this doesn’t meet the requirement.

For the MediaStore

This api can be used to create file in the public folder, but the file can just be accessed by the app which create it. When user uninstall the application, you can’t access it either.

And the google suggest the developer use the ACTION_CREATE_DOCUMENT to let the user create a file by himself and then user can open it by the ACTION_OPEN_DOCUMENT.

So even though the Android.OS.Environment.GetExternalStoragePublicDirectory method has marked as deprecated, it is the easier way to get the result you want.

For more information, you can check this case and the official document.

Answered By – Liyun Zhang – MSFT

Answer Checked By – Terry (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published