Im developing an Android app using the Xamarin platform and Im trying to create a folder on my local storage but I have had no success.
First I tried using the System.IO namespace through a FileManager class created by Xamarin Forms Labs. A snippet of the functions I was passing the path of "/storage/emulated/0/`".
public void CreateDirectory(string path)
{
this.isolatedStorageFile.CreateDirectory(path);
}
public Stream OpenFile(string path, FileMode mode, FileAccess access)
{
return (Stream)this.isolatedStorageFile.OpenFile(path, (System.IO.FileMode)mode, (System.IO.FileAccess)access);
}
This didn't work so I then opted to using PCLStorage a library for cross platform file operations. I tried this code.
IFolder rootFolder = FileSystem.Current.LocalStorage;
folder = await rootFolder.CreateFolderAsync("wakesocial",
CreationCollisionOption.OpenIfExists);
Didn't work. I navigated to the root of the internal storage and I didn't see the folder.
So the error doesn't seem to be occurring because of the libraries in use but something specific to Android. I have read and write to external storage in manifest. So the question is. Does an app have permission to create a file or folder at the root level of the storage device or does it have to create it at particular location such as in Android/data/packagename
string folderPath = Environment.ExternalStorageDirectory.AbsolutePath; //Android
public async Task PCLGenaratePdf(string folderPath )
{
IFolder rootFolder = await FileSystem.Current.GetFolderFromPathAsync(folderPath );
IFolder folder = await rootFolder.CreateFolderAsync("folder", CreationCollisionOption.OpenIfExists);
IFile file = await folder.CreateFileAsync("file.pdf", CreationCollisionOption.ReplaceExisting);
}
After lot of trying I solved this problem with this
string rootPath = Android.App.Application.Context.GetExternalFilesDir(null).ToString();
var filePathDir = Path.Combine(rootPath, "Folder");
if (!File.Exists(filePathDir))
{
Directory.CreateDirectory(filePathDir);
}
The folder created is reachable through adb @ /sdcard/Android/Data/Folder or something like this, or in device memory @ /Android/data/<< AppName >>/files/Folder
On Android, PCL Storage's LocalStorage folder corresponds to the "My Documents" Special Folder.
I'm not sure exactly what path you're trying to create a folder in, but if you know the path and want to use PCL Storage, you should be able to use FileSystem.Current.GetFolderFromPathAsync
to get a PCL Storage IFolder
corresponding to an existing folder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With