添加的ConnectionString中的app.config [英] Add connectionstring in app.config
问题描述
我在C#类库已经有几个班和一个app.config中。我已经把在ConnectionString中的app.config如下:
I have a class library in C# has has several classes and a app.config. I have put ConnectionString in app.config as follows:
<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>
我尝试在我的项目中的一个类打开连接字符串如下:
I try to open connection string in one of the classes in my project as follows:
string connectionString = ConfigurationManager.ConnectionStrings["TRN_DB"].ConnectionString.ToString();
SqlConnection con = new SqlConnection(connectionString);
con.Open();
但它给了我一个错误:
But it gave me an error as:
{未将对象引用设置到对象的实例。}
{"Object reference not set to an instance of an object."}
连接字符串是正确的,当我在Web项目中使用同样的方法在web.config内,是否有人知道如何如何,我可以在app.config中访问它?我已经使用这种方式太:
The connection string is correct when I use same way in web project inside the web.config, Does anybody know how how I can access it in app.config? I already use it this way too:
string connectionString = System.Configuration.ConfigurationSettings.AppSettings["TRN_DB"];
这人给我这个错误:
这方法已过时,它已取代System.Configuration!System.Configuration.ConfigurationManager.Appsettings
This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.Appsettings
要清楚,我没有在我的解决方案的其他项目,我希望我的类库独立工作。我不能够应用的web项目,并web.config中说。所以,我不是要补充连接字符串的app.config和访问它,或者一个web.config添加到我的类库项目。那我不知道哪一个是可行的。
To make it clear, I don't have any other project in my solution, as I want my class library to work independently. I am not able to app web project and web.config to that. So I either should add connection string to app.config and access it Or add a web.config to my class library project. That I am not sure which one is doable.
推荐答案
如果您运行的是网络与类项目图书馆,
连接字符串添加到的web.config
在网站项目
If you are running Web project with Class library,
add connection string to web.config
inside the Web project
如果您正在运行的控制台/ WinForm的与类库,
连接字符串添加到的app.config
里面的项目在控制台/ WinForm的项目
If you are running Console/WinForm project with Class library,
add connection string to app.config
inside the Console/WinForm project
修改的库项目不会工作你的情况配置。
modifying config in Library project will not work in your case.
这篇关于添加的ConnectionString中的app.config的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!