7

我正在部署一个用 vs 2008 0n XP sp3 构建的 winform 应用程序。

我创建了一个带有空架构的数据库,我将其放在项目的根文件夹和我选择的属性中Build Action嵌入式资源Copy to Output directory始终复制。现在,我没有在 app.config connectionString 部分中使用连接字符串,而是在appSettingkey=“database”;中输入了一个条目。value="mydb.db;版本=3"。

所以要创建我的connectionString我使用:

 SQLiteConnection con = new SQLiteConnection("Data Source=" + Path.Combine(Application.StartupPath, ConfigurationManager.AppSettings["database"]));

一切正常,我将应用程序与安装项目打包在一起。现在,在我安装应用程序后,找不到数据库,我不得不将数据库复制到Application Folder安装项目中以使其工作。

我认为db应该在应用程序dll中,因为.copy always但我无法访问它。那么我到底做错了什么?

我怀疑我应该刚刚连接到根数据库,意思是不使用Application.StartupPath

但是我在这里要求最佳实践,因为我所做的工作有效,但看起来仍然像解决方法,所以请任何人都可以与我分享他的经验吗?谢谢阅读

4

1 回答 1

5

Embedded Resource意味着数据库嵌入到您的 dll 中。该Copy to output directory设置在这种情况下不适用,用于Build Action: Content.

嵌入数据库后,您基本上必须在第一次使用时取消嵌入它。为此,将其从程序集中读取并将其存储到文件中。

class EmbeddedResourceTest
{
    public static void Test()
    {
        string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Test.db");

        using(var resourceStream = typeof(EmbeddedResourceTest).Assembly.GetManifestResourceStream("Test.db"))
        {
            using(var fileStream = File.OpenWrite(path))
            {
                CopyStream(resourceStream, fileStream);
            }
        }

        // now access database using 'path'
    }

    public static void CopyStream(Stream inputStream, Stream outputStream)
    {
        CopyStream(inputStream, outputStream, 4096);
    }

    public static void CopyStream(Stream inputStream, Stream outputStream, int bufferLength)
    {
        var buffer = new byte[bufferLength];
        int bytesRead;
        while ((bytesRead = inputStream.Read(buffer, 0, bufferLength)) > 0)
        {
            outputStream.Write(buffer, 0, bytesRead);
        }
    }
}
于 2010-04-23T03:35:01.120 回答