我自己写了一个类,以便在项目里调用
public class DataConfig { private static string _connString; private static string _connString1; public static string ConnString1 { get { return DataConfig._connString1; } set { DataConfig._connString1 = value; } } public static string ConnString { get { return DataConfig._connString; } set { DataConfig._connString = value; } } static DataConfig() { AppSettingsReader obj = new AppSettingsReader(); //获取承载在当前应用程序域中的应用程序的应用程序目录的物理驱动器路径。 string WebConfigDirectory = HttpRuntime.AppDomainAppPath; string path = WebConfigDirectory + "setup\\Web2.config"; XmlDocument xd = new XmlDocument(); xd.Load(path); //如果没有appSetting,则添加 if (xd.SelectNodes("appSettings").Count == 0) { xd.DocumentElement.AppendChild(xd.CreateElement("appSettings")); } //遍历XML 文档(配置文件)然后给其属性赋值 foreach (XmlNode xn1 in xd.SelectNodes("/configuration/appSettings/add")) { if (xn1.Attributes["key"].Value == "ConnString") { _connString = xn1.Attributes["value"].Value; } } } }
然后在cs页面里调用
string connstring = DataConfig.ConnString;
webconfig 页面里
<?xml version="1.0"?> <configuration> <appSettings> <!--链接数据库--> <add key="ConnString" value="server=192.168.1.112;uid=sa;pwd=jinzhao123456;database=PeopleDataCenter; Max Pool Size=500; Min Pool Size=1"/> <add key="ConnString1" value="server=192.168.1.112;uid=sa;pwd=jinzhao123456;database=PeopleDataCenter; Max Pool Size=500; Min Pool Size=1"/> </appSettings> <system.web> <compilation debug="false" targetFramework="4.0" /> </system.web> </configuration>
学习在于积累,积少成多,努力。。。。