.net App.config 连接字符串相对路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5001980/
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-09-03 15:15:49  来源:igfitidea点击:

App.config connection string relative path

.netsqliteconfigurationconnection-stringapp-config

提问by Radu D

I need to set in the app.config the sqlite connection string. I want to set the path relative to the debug/release folders the database file will be copied to those folders.

我需要在 app.config 中设置 sqlite 连接字符串。我想设置相对于数据库文件将被复制到这些文件夹的调试/发布文件夹的路径。

<add name="EmailsSQLite" connectionString="data source=c:\Users\Test\Documents\Visual Studio 2008\Projects\TestConsole\Emails\data\EmailDatabase.sqlite" providerName="System.Data.SQLite"/>

and I want to have something like:

我想要一些类似的东西:

<add name="EmailsSQLite" connectionString="data source=\data\EmailDatabase.sqlite" providerName="System.Data.SQLite"/>

Is that possible?

那可能吗?

回答by Joe

You can specify a relative path as described in Lefty's answer.

您可以指定一个相对路径,如 Lefty 的回答中所述。

However this will be relative to the current working directory, which will not necessarily be the directory containing your executable.

然而,这将是相对于当前工作目录的,它不一定是包含可执行文件的目录。

One way round this is to modify the connection string before using it, e.g.

解决此问题的一种方法是在使用之前修改连接字符串,例如

In app.config:

在 app.config 中:

 connectionString="data source={AppDir}\data\EmailDatabase.sqlite

In your code:

在您的代码中:

ConnectionStringSettings c = ConfigurationManager.ConnectionStrings[name];    
if (c == null)
{
    ... handle missing connection string ...
}
string fixedConnectionString = c.ConnectionString.Replace("{AppDir}", AppDomain.CurrentDomain.BaseDirectory);
... use fixedConnectionString

回答by bluekushal

Yes it is possible. Try using |DataDirectory|.

对的,这是可能的。尝试使用 |DataDirectory|。

In App.config

在 App.config 中

<add name="SqliteConnectionString" connectionString="Data Source=|DataDirectory|\Database.sqlite;" providerName="System.Data.SQLite"/>

More information on this page https://msdn.microsoft.com/en-us/library/cc716756.aspx

有关此页面的更多信息 https://msdn.microsoft.com/en-us/library/cc716756.aspx

回答by Lefty

Try using a "." before the first backslash in the data source part of the string.

尝试使用“。” 在字符串的数据源部分中的第一个反斜杠之前。

eg.

例如。

data source=.\data\EmailDatabase.sqlite