我在 C# 中有一个类库,它有几个类和一个 app.config。我已将 ConnectionString 放入 app.config 中,如下所示:
<connectionStrings>
<add name="TRN_DB"
connectionString="Database=TRN;Server=NDTSSN;User ID=ln_users2;Password=%4nu$r!;Connection Timeout=30;pooling=false;"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
我尝试在我的项目中的一个类中打开连接字符串,如下所示:
string connectionString = ConfigurationManager.ConnectionStrings["TRN_DB"].ConnectionString.ToString();
SqlConnection con = new SqlConnection(connectionString);
con.Open();
但它给了我一个错误:
{"Object reference not set to an instance of an object."}
当我在 web.config 中的 web 项目中使用相同的方式时,连接字符串是正确的,有人知道我如何在 app.config 中访问它吗?我也已经这样使用了:
string connectionString = System.Configuration.ConfigurationSettings.AppSettings["TRN_DB"];
这个给我这个错误:
This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.Appsettings
明确地说,我的解决方案中没有任何其他项目,因为我希望我的类库独立工作。我无法将 web 项目和 web.config 应用到那个。所以我要么应该将连接字符串添加到 app.config 并访问它,要么将 web.config 添加到我的类库项目中。我不确定哪个可行。
最佳答案
如果您正在使用类库运行Web 项目,
将连接字符串添加到 Web 项目中的 web.config
如果您正在使用类库运行 Console/WinForm 项目,
将连接字符串添加到 Console/WinForm 项目中的 app.config
修改库项目中的配置不适用于您的情况。
关于c# - 在 app.config 中添加连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17309797/