You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI跨平台应用正确文件保存路径解决方案咨询

最佳文件路径解决方案与问题解释

获取正确保存路径的最佳方式

根据你的需求(优先通用性、备份文件可访问),推荐两种方案:

1. 跨平台通用的用户可见路径(推荐)

使用MAUI内置的FileSystem.GetFolderAsync(SpecialFolder.MyDocuments),该API会自动适配各平台的用户易访问目录:

  • Android:对应/storage/emulated/0/Documents(公共文档目录,用户直接可见)
  • iOS:对应应用沙盒内的/Documents(可通过系统"文件"应用访问)
  • Windows:对应C:\Users\[用户名]\Documents

代码示例:

public async Task WriteAppDataFileAsync()
{
    if (AppData.User != null)
    {
        try
        {
            string fileName = $"backup_user{AppData.User.Id}.json";
            string history = AppData.User.History;

            var documentsFolder = await FileSystem.Current.GetFolderAsync(SpecialFolder.MyDocuments);
            var filePath = Path.Combine(documentsFolder.Path, fileName);

            File.WriteAllText(filePath, history);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

2. 应用专属外部存储目录(匹配你硬编码的路径,跨平台适配)

如果希望备份文件放在应用专属的外部存储目录(卸载应用时会自动删除,且用户可在文件管理器找到),可以通过条件编译实现跨平台兼容:

public string GetAppExternalStorageDir()
{
#if ANDROID
    return Android.App.Application.Context.GetExternalFilesDir(null)?.AbsolutePath ?? string.Empty;
#elif IOS
    return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
#elif WINDOWS
    return Windows.Storage.ApplicationData.Current.LocalFolder.Path;
#else
    return FileSystem.Current.AppDataDirectory;
#endif
}

public void WriteAppDataFile()
{
    if (AppData.User != null)
    {
        try
        {
            string fileName = $"backup_user{AppData.User.Id}.json";
            string history = AppData.User.History;

            string saveDirectory = GetAppExternalStorageDir();
            var filePath = Path.Combine(saveDirectory, fileName);

            File.WriteAllText(filePath, history);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

Android端使用GetExternalFilesDir(null)会直接返回不带Documents后缀的应用专属外部存储路径,和你硬编码的路径完全一致。


为什么FileSystem.Current.AppDataDirectory在手机中找不到?

AppDataDirectory在Android上对应应用内部存储路径(/data/user/0/com.mycompany.myapp/files):

  • 该路径是应用私有目录,默认不会在文件管理器中显示(需开启"显示隐藏文件"选项才能看到);
  • 只有当前应用拥有该目录的读写权限,其他应用无法访问;
  • 代码能正常写入是因为应用本身拥有该目录的权限,只是用户默认看不到而已。

内容的提问来源于stack exchange,提问作者GChapX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 16:26:00