代码之家  ›  专栏  ›  技术社区  ›  meeth_

.NET MAUI-如何写入/storage/emulated/0/Documents?

  •  1
  • meeth_  · 技术社区  · 6 月前

    我正试图将文件从我的应用程序文件夹复制到公共文档文件夹,以便在需要时可以访问它。我正在为Android操作系统编写此代码。这是我到目前为止的代码:

    string sourceDirectoryPath = Path.Combine(FileSystem.Current.AppDataDirectory, "Logs");
    
    if (!Directory.Exists(sourceDirectoryPath))
    {
        //No logs
    
        return;
    }
    
    string documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    
    string destinationDirectoryPath = Path.Combine(documentsFolder, "Logs");
    
    if (!Directory.Exists(destinationDirectoryPath))
    {
        Directory.CreateDirectory(destinationDirectoryPath);
    }
    
    foreach (string file in Directory.GetFiles(sourceDirectoryPath))
    {
        string destinationFile = Path.Combine(destinationDirectoryPath, Path.GetFileName(file));
        File.Copy(file, destinationFile, overwrite: true);
    }
    

    我试过使用 Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); ,但它指向 /data/user/0/MyApp/files/Documents .我怎么做 documentsFolder 指向 /storage/emulated/0/Documents ?

    1 回复  |  直到 6 月前
        1
  •  2
  •   Rafael Bhavanesh N    6 月前

    当然, Environment.SpecialFolder.MyDocuments; 将返回应用程序的“个人文档”文件夹。

    要获取公共文档文件夹路径,请尝试以下操作。

    string documentsPath = string.empty;
    #if ANDROID
     documentsPath = global::Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryDocuments)?.AbsolutePath;
    #endif