I tried this but getting System.UnauthorizedAccessException: 'Access to the path "/storage/emulated/0/Download/myfile.txt" is denied
Hi, @Sreejith Sree . Android 10 introduced a new storage paradigm for apps called scoped storage which changes the way apps store and access files on a device's external storage. If you target Android 10 (API level 29) or higher, set the value of android:requestLegacyExternalStorage
to true in your app's manifest file.
Check the doc: https://developer.android.com/training/data-storage/use-cases#opt-out-scoped-storage
I need a create a folder first, then a text file on that folder
You could use File.Exists(xx)
to check if the folder exists, and use Directory.CreateDirectory(xx)
to create the folder if not. Check the code:
[assembly: Xamarin.Forms.Dependency(typeof(AccessFileImplement))]
namespace TestApplication.Droid
{
public class AccessFileImplement : IAccessFileService
{
void IAccessFileService.CreateFile(string FileName)
{
string text = "hello world";
byte[] data = Encoding.ASCII.GetBytes(text);
string rootPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
var filePathDir = Path.Combine(rootPath, "folder");
if (!File.Exists(filePathDir))
{
Directory.CreateDirectory(filePathDir);
}
string filePath = Path.Combine(filePathDir, FileName);
File.WriteAllBytes(filePath, data);
}
}
}