It'd be convenient if an application I'm writing stored some files to external storage permanently (so they persist after the application has been exited[destroyed]/Uninstalled). I want to take database backup and store some cache and log files. I am targeting Android-11 while previously I was having access to external storage. Is there any way I can have these files not to be removed on an uninstall? Help with example will be really appreciated.
1 Answers
You could save the file to the storage directory for public files on external storage as PUBLIC_EXTERNAL_STORAGE
. https://learn.microsoft.com/en-us/xamarin/android/platform/files/external-storage?tabs=windows
I use the Download folder for example.
var DIR= Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads);
var FILE=DIR + "/test.txt";
using (FileOutputStream outfile = new FileOutputStream(FILE))
{
string line = "The very first line!";
outfile.Write(System.Text.Encoding.ASCII.GetBytes(line));
outfile.Close();
}
Xamarin.Forms does not provide the api to access External storage, we have to implement it in each specific platform. You could use the Dependency Service. https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/introduction
Here is an example of denpendence service for your reference. Save image from an image box to gallery in Xamarin Forms
Starting with Android 6.0 or higher, we need a runtime permission check. You could check the example I down before. Xamarin.Forms WebView not working with WebRTC

- 10,509
- 1
- 7
- 17
-
Hi, thankyou for your reply. I have mentioned Xamarin.android in tag below the question. My basic concern is " files not to be removed on app uninstall". Your provided code will only create the file but it will get deleted on app uninstall. Can you help me in this regard. thanks for your support. – user6159419 Oct 21 '20 at 15:52
-
The point is to put the files in public external storage not the code to create the file. The code I provided is used to show that creating a file in public external download folder. When i delete the file i created, the file is stil in the download folder. – Wendy Zang - MSFT Oct 22 '20 at 08:27