1

我有一个使用 SQL Server Compact.SDF数据库存储数据的 Winforms 应用程序。调试时应用程序在 Visual Studio 中运行良好,但是当我使用项目的“发布”选项并在安装后运行程序时,我总是收到错误消息“找不到数据库文件”。

我将连接字符串设置如下

string fileName = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "Cellar.sdf");
connString = string.Format("Data Source={0};", fileName);

数据库Cellar.sdf在我的程序文件夹中。

在此处输入图像描述

很明显,数据库的路径是错误的,但是有没有办法让我在使用“发布”功能时设置我希望安装应用程序的路径,或者找出数据库文件的位置抄袭?在桌面应用程序中包含本地数据库文件的正确方法是什么?

4

1 回答 1

1

您可以包含 DataDirectory 宏,并将位置设置到代码中的合适位置。

connString = string.Format("Data Source=|DataDirectory|\{0};", fileName);

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        // This is our connection string: Data Source=|DataDirectory|\Chinook40.sdf
        // Set the data directory to the users %AppData% folder
        // So the Chinook40.sdf file must be placed in:  C:\\Users\\<Username>\\AppData\\Roaming\\
        AppDomain.CurrentDomain.SetData("DataDirectory", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
    }

这将要求您在初始应用程序启动期间将数据库文件复制到所需位置(如果它不存在)。

于 2013-08-28T07:10:56.103 回答