I am trying to merge some txt-Files from a folder in a Xamarin Form app.
The path is selectable by the user (i´ve created a simple folder browser for that).
e.g. the source path is
/storage/1EE7-170F/
I collect e.g. all txt-files in that folder, read them using File.ReadAllText, do some processing. That is working fine so far.
I also want to write the results to a new file in the same folder using File.WriteAllText. Target file would be:
/storage/1EE7-170F/SomeResultFile.txt
Getting the directories content is in AppName.Android:
var fileContents = Directory.GetFiles(baseDirectory.FullPath, searchPattern)
.Select(fullPath =>
{
var fileName = Path.GetFileName(fullPath);
var extension = Path.GetExtension(fullPath);
return new FileContent(fileName, fullPath, extension);
});
Reading of the files goes like this in common project:
var content = File.ReadAllText(fileContent.FullPath);
The files are written like this (also in common project):
var baseDir = Path.GetDirectoryName(sourceFiles.First().FullPath);
var targetFilePath = Path.Combine(baseDir, filename);
File.WriteAllLines(targetFilePath, lines);
But i always get an UnauthorizedAccessException saying 'Access to the path "/storage/1EE7-170F/SomeResultFile.txt" is denied.'
I wonder why i can read from that folder, but not write to it.
Writing to System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) is working fine, but that´s not what i need. I need the result files in the same directory as the source files.
I have both permission "READ_EXTERNAL_STORAGE" and "WRITE_EXTERNAL_STORAGE" enabled in the manifest.
In MainActivity.OnCreate i have added the following:
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)
{
ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.WriteExternalStorage }, 0);
}
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted)
{
ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.ReadExternalStorage }, 0);
}
I´ve tried that both on Android emulator and a S10 with latest Android installed (on S10 i selected the "Documents" folder). Same result on both systems with different folders...
Any ideas what could be the problem?
Thanks a lot for help!