C# 使用 System.Data.SQLite,如何使用相对路径在连接字符串中指定数据库文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/314853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 22:50:53  来源:igfitidea点击:

With System.Data.SQLite how do you specify a database file in the connect string using a relative path

c#sqliteconnection-stringsystem.data.sqlite

提问by minty

Wanting to deploy my project on different servers I would prefer to be able to specify a connect string using a relative path. I can't seem to get that to work and want to know if there is some trick to it...?

想要在不同的服务器上部署我的项目,我希望能够使用相对路径指定连接字符串。我似乎无法让它发挥作用,想知道它是否有什么技巧......?

回答by AJ.

A suggestion

一条建议

You could build the absolute path in the app and pass that in the connection string.

您可以在应用程序中构建绝对路径并将其传递到连接字符串中。

So, if you know that the database file is in the databasesubfolder of the application folder, you could do something like this (C#):

因此,如果您知道数据库文件位于database应用程序文件夹的子文件夹中,您可以执行以下操作(C#):

    string relativePath = @"database\myfile.s3db";
    string currentPath;
    string absolutePath;
    string connectionString;

    currentPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
    absolutePath = System.IO.Path.Combine(currentPath,relativePath);

    connectionString = string.Format("DataSource={0}", absolutePath);

    SQLiteConnection cnn = new SQLiteConnection(connectionString);

(Someone can probably correct me on how to get the current path).

(有人可能会纠正我如何获得当前路径)。

回答by AJ.

Like this:

像这样:

String currentPath = System.IO.Path.GetDirectoryName( Application.ExecutablePath );

String currentPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);

回答by trendl

How about this?

这个怎么样?

"Data Source=|DataDirectory|mydb.db;..."

I believe |DataDirectory|point to the directory where your app is located. I use NHibernate and it works with the following:

我相信|DataDirectory|指向您的应用程序所在的目录。我使用 NHibernate,它适用于以下内容:

<add key="hibernate.connection.connection_string"
       value="Data Source=|DataDirectory|mydb.db;Version=3;Compress=False;synchronous=OFF;" >