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

迁移至.NET MAUI后如何正确访问Xamarin.Forms创建的应用数据文件?

迁移Xamarin.Forms到MAUI时的SQLite数据库路径兼容方案

在Android平台上,Xamarin.Forms与MAUI对Environment.SpecialFolder.LocalApplicationData的实现存在差异:

  • Xamarin.Forms中该路径指向/data/user/0/[包名]/files/.local/share
  • MAUI中该路径直接指向/data/user/0/[包名]/files

这种差异导致MAUI无法直接访问Xamarin.Forms创建的SQLite数据库,以下是更可靠的兼容方案,替代硬编码路径片段的临时解决方法:

正确实现代码

public static string DatabasePath
{
    get
    {
#if ANDROID
        // 直接获取Xamarin.Forms使用的原始基础路径
        var androidFilesDir = Android.App.Application.Context.FilesDir.AbsolutePath;
        var basePath = Path.Combine(androidFilesDir, ".local/share");
#else
        // 其他平台保持原有逻辑不变
        var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
#endif
        return Path.Combine(basePath, "mydb.db3");
    }
}

方案优势

  • 避免硬编码路径判断的脆弱性:依赖Android系统API获取标准的files目录,而非依赖Environment.GetFolderPath的返回格式,即使未来MAUI的路径实现变更,该逻辑依然有效。
  • 完全匹配Xamarin.Forms的原始路径:直接复用Xamarin.Forms使用的.local/share子目录,确保数据库文件的访问路径完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 21:07:47