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

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

问题描述

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

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>

当我尝试使用以下 C# 代码片段获取此连接字符串时,我得到值 null.我无法获取连接字符串.语法有问题吗?

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?

第一次尝试:

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

第二次尝试:

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

推荐答案

对于非 Web 项目,并且在 OP 中设置 app.config 这就是我通常做的事情,因为配置文件在应用程序时更改名称编译(到 yourapp.exe.config):

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);
    }

然后引用第s个连接字符串:

Then to reference the s'th connection string:

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

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

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