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

如何发布含SQLite数据库的UWP应用?发布后崩溃无法保存数据

问题核心原因

UWP应用的安装目录是只读的,你当前连接字符串指向的是安装目录下的数据库文件,发布后写入操作会触发权限异常,直接导致应用崩溃;而调试模式下应用运行在可写的输出目录,因此能正常保存数据。


解决方案步骤

1. 修正数据库文件的项目设置

  • 将数据库文件的生成操作改为「内容」(之前设为「生成」错误,「生成」仅针对编译类文件)
  • 保持「复制到输出目录」为「较新则复制」
  • 发布设置中确认文件标记为「包含」「必需」「数据文件」

2. 运行时复制初始数据库到可写目录

UWP的ApplicationData.Current.LocalFolder是应用专属的可写目录,第一次启动时需将安装目录中的初始数据库复制到此处,后续所有操作都针对这个副本:

private async Task CopyDatabaseToLocalFolderAsync()
{
    string localDbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "FDb.db");
    if (!File.Exists(localDbPath))
    {
        StorageFile dbFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///FDb.db"));
        await dbFile.CopyAsync(ApplicationData.Current.LocalFolder, "FDb.db", NameCollisionOption.ReplaceExisting);
    }
}

在应用启动时调用(例如App.xaml.cs的OnLaunched方法):

protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
    await CopyDatabaseToLocalFolderAsync();
    // 其他启动逻辑...
}

3. 动态生成连接字符串

不能使用固定相对路径,需动态指向LocalFolder中的数据库文件:

public class DogContext : DbContext
{
    public DbSet<Dog> Dog { get; set; }

    public DogContext() : base(GetConnectionString())
    {
    }

    private static string GetConnectionString()
    {
        string dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "FDb.db");
        return $"Data Source={dbPath};Version=3";
    }
}

4. 修复实体类和按钮事件的潜在问题

  • 实体类主键设置自动生成,避免手动赋值导致冲突:
public class Dog
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string Name { get; set; }
}
  • 按钮事件中使用using释放DbContext资源,避免内存泄漏:
private void Button_Click(object sender, RoutedEventArgs e)
{
    using (DogContext context = new DogContext())
    {
        context.Dog.Add(new Dog() { Name = txtbxName.Text });
        context.SaveChanges();
        List<Dog> Dogs = context.Dog.ToList();
        // 绑定到UI的逻辑...
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:20:00