例如:
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="EMSConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=db_CMS;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
web.config
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings>
<add name="EMSConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=db_CMS;Integrated Security=True"/>
</connectionStrings>
<system.web>
<!--
设置 compilation debug="true" 可将调试符号插入
已编译的页面中。但由于这会
影响性能,因此只在开发过程中将此值
设置为 true。
-->
<compilation debug="true">
</compilation>
<!--
通过 <authentication> 节可以配置 ASP.NET 用来
识别进入用户的
安全身份验证模式。
-->
<authentication mode="Windows"/>
<!--
如果在执行请求的过程中出现未处理的错误,
则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,
开发人员通过该节可以配置
要显示的 html 错误页
以代替错误堆栈跟踪。
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
</system.web>
</configuration>
C#读取connectionstring
1.string str= System.Configuration.ConfigurationManager.ConnectionStrings["EMSConnectionString"].ConnectionString.ToString();或
string str = System.Configuration.ConfigurationSettings.AppSettings["EMSConnectionString"].ToString();
注意:ConnectionStrings["EMSConnectionString"]这里中括号里面的是对应name="EMSConnectionString"的值,
如果name="EMSConnectionString",那么应该为:ConnectionStrings["EMSConnectionString"]。
2.如果使用Properties栏目的Settings.settings来设置,则有以下方法读取:
string str=Properties.Settings.Default.EMSConnectionString;
这句话跟上面的例子的效果一样,能够获取到字符串。
3.换种方式,指定具体文件
private static string GetConnectionStringsConfig(string connectionName)
{
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = Application.StartupPath + @"\sss.exe.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
return config.ConnectionStrings.ConnectionStrings[connectionName].ConnectionString.ToString();
}
VBnet读取
1.Dim str As String= System.Configuration.ConfigurationSettings.AppSettings("EMSConnectionString")
2. My.Settings.EMSConnectionString
C#动态读取config文件
public string GetConfigValue(string path,string appKey){
XmlDocument xDoc = new XmlDocument();
Try
{
xDoc.Load(path);
//xDoc.Load(System.Windows.Forms.Application.ExecutablePath+".config");
XmlNode xNode;
XmlElement xElem;
xNode = xDoc.SelectSingleNode("//appSettings");
xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='"+appKey+"']");
If (xElem! = null) Then
return xElem.GetAttribute("value");
Else
return "";
}
catch(Exception)
{
return "";
}
}