App.config 连接字符串相对路径 [英] App.config connection string relative path

查看:33
本文介绍了App.config 连接字符串相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

我想要这样的东西:

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

这可能吗?

推荐答案

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

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

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

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.

在 app.config 中:

In app.config:

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

在您的代码中:

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

这篇关于App.config 连接字符串相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆