从 web.config 读取连接字符串
如何将 web.config
文件中的连接字符串读取到类库中包含的公共类中?
我已经尝试过了:
WebConfigurationManager
ConfigurationManager
但是这些类在我的类库中未被识别。
How can I read a connection string from a web.config
file into a public class contained within a class library?
I've tried:
WebConfigurationManager
ConfigurationManager
But these classes are not recognized within my class library.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
您需要添加对 System.Configuration 的引用,然后使用:
You need to add a reference to
System.Configuration
and then use:添加
System.Configuration
作为参考。由于某些奇怪的原因,它默认不包含在内。
Add
System.Configuration
as a reference.For some bizarre reason it's not included by default.
C#
VB
C#
VB
添加
System.Configuration
作为参考,然后:Add
System.Configuration
as a reference then:我想您需要添加对 System.Configuration 程序集的引用(如果尚未添加)。
此外,您可能需要在代码文件的顶部插入以下行:
I guess you need to add a reference to the System.Configuration assembly if that have not already been added.
Also, you may need to insert the following line at the top of your code file:
C#
WEB.CONFIG 文件代码下面的
在上面的代码中 ABCD 是连接名称
C#
BELOW WEB.CONFIG FILE CODE
In the above Code ABCD is the Connection Name
在
VB
中:这应该可以在
C#
中工作(根据 Ala 的评论)In
VB
: This should workIn
C#
it would be (as per comment of Ala)您必须在页面或类的顶部调用此类:
然后您可以使用此方法返回连接字符串,准备传递给 sqlconnection 对象以继续您的工作,如下所示:
只是为了明确说明,这是网络配置中的值:
You have to invoke this class on the top of your page or class :
Then you can use this Method that returns the connection string to be ready to passed to the sqlconnection object to continue your work as follows:
Just to make a clear clarification this is the value in the web Config:
请记住不要使用 ConnectionStrings[index] 因为您可能会使用全局计算机配置和可移植性
Remember don't Use ConnectionStrings[index] because you might of Global machine Config and Portability
首先添加这个:
First add this:
每个人似乎都在建议添加
哪个是正确的。
但我是否可以建议您考虑安装 ReSharper 的 Visual Studio 扩展?
安装后,您不会看到未定义类的错误,而是会看到一条提示,告诉您该类位于哪个程序集中,询问您是否希望它添加所需的 using 语句。
Everybody seems to be suggesting that adding
which is true.
But might I suggest that you think about installing ReSharper's Visual Studio extension?
With it installed, instead of seeing an error that a class isn't defined, you'll see a prompt that tells you which assembly it is in, asking you if you want it to add the needed using statement.
添加命名空间 System.Configuration 作为参考
Add Namespace System.Configuration as a reference then