从AppConfig的文件在C#中提取连接字符串 [英] Fetching connection string from appconfig file in c#

查看:236
本文介绍了从AppConfig的文件在C#中提取连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在的app.config 文件中声明下面的连接字符串:

 <&是connectionStrings GT; 
<添加名称=SqlConnectionString的connectionString =数据源= xxx.xx.xx.xx;初始目录= XXXXX;用户ID = XX;密码= XXX;的providerName =System.Data.SqlClient的/>
< /&是connectionStrings GT;

当我尝试使用下面的C#代码段来获取此连接字符串,我得到的值。我不能获得连接字符串。 ?这有什么错的语法



第一次尝试:

  VAR设置= ConfigurationManager.ConnectionStrings [SqlConnectionString]; 
字符串结果= settings.ConnectionString;



第二次尝试:

 字符串结果= ConfigurationSettings.AppSettings [SqlConnectionString]; 


解决方案

对于非web项目,并与应用。配置设置在这里的OP就是我通常做的,因为它们的配置文件更改名称,当应用程序被编译(到yourapp.exe.config):

 公共静态配置ExeConfig()
{
组装服务= Assembly.GetAssembly(typeof运算(YourClass));
返回ConfigurationManager.OpenExeConfiguration(service.Location);
}



然后引用第S连接字符串:

  ExeConfig()。ConnectionStrings.ConnectionStrings [S] .ConnectionString 


I have the following connection string declared in my app.config file:

  <connectionStrings>
    <add name="SqlConnectionString" connectionString="Data Source=xxx.xx.xx.xx;Initial Catalog=xxxxx;User Id=xx;Password=xxx;" providerName="System.Data.SqlClient" />
  </connectionStrings>

When I try to fetch this connection string using the following C# code snippet, I get the value null. I am not able to obtain the connection string. Is there anything wrong in the syntax?

First attempt:

var settings = ConfigurationManager.ConnectionStrings["SqlConnectionString"];
string result = settings.ConnectionString;

Second attempt:

string result = ConfigurationSettings.AppSettings["SqlConnectionString"];

解决方案

For a non-web project, and with app.config set up as in the OP here's what I usually do, since the config file changes names when the app is compiled (to yourapp.exe.config):

    public static Configuration ExeConfig()
    {
        Assembly service = Assembly.GetAssembly(typeof(YourClass));
        return ConfigurationManager.OpenExeConfiguration(service.Location);
    }

Then to reference the s'th connection string:

ExeConfig().ConnectionStrings.ConnectionStrings[s].ConnectionString

这篇关于从AppConfig的文件在C#中提取连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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