不能用PCLStorage或Xamarin Forms Labs在Android文件系统中创建文件夹/文件

本文关键字:文件系统 创建 文件夹 文件 Android PCLStorage Xamarin Labs Forms 不能 | 更新日期: 2023-09-27 17:50:20

我正在使用Xamarin平台开发一个Android应用程序,我试图在本地存储上创建一个文件夹,但我没有成功。

首先我尝试使用系统。通过Xamarin Forms Labs创建的FileManager类创建IO命名空间。我传递给"/storage/emululated/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);
        }

这不起作用,所以我选择使用PCLStorage一个跨平台文件操作库。我试过这个代码。

IFolder rootFolder = FileSystem.Current.LocalStorage;
folder = await rootFolder.CreateFolderAsync("wakesocial",
                CreationCollisionOption.OpenIfExists);

不工作。我导航到内部存储的根目录,但没有看到文件夹。

所以错误似乎不是因为使用的库而发生的,而是Android特有的东西。我已经在清单中读写外部存储。问题是。应用程序是否有权限在存储设备的根级别创建文件或文件夹,还是必须在特定位置创建文件或文件夹,例如Android/data/packagename

不能用PCLStorage或Xamarin Forms Labs在Android文件系统中创建文件夹/文件

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);
    }

经过多次尝试,我用这个

解决了这个问题
        string rootPath = Android.App.Application.Context.GetExternalFilesDir(null).ToString();
        var filePathDir = Path.Combine(rootPath, "Folder");
        if (!File.Exists(filePathDir))
        {
            Directory.CreateDirectory(filePathDir);
        }

创建的文件夹可通过adb @/sdcard/Android/Data/folder或类似的东西访问,或在设备内存@/Android/Data/<<浏览器名称>>/文件/文件夹

在Android上,PCL Storage的LocalStorage文件夹对应于"My Documents"特殊文件夹。

我不确定你试图创建文件夹的确切路径,但如果你知道路径并想使用PCL存储,你应该能够使用FileSystem.Current.GetFolderFromPathAsync来获得与现有文件夹对应的PCL存储IFolder