C# 读取和设置app.config里的connectionstring

//第一种获取连接字符串的方法 
Properties.Settings connset = Properties.Settings.Default; 
constr = connset.ConnectionString; 
     
         
//第二种获取连接字符串的方法 
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["ConnectionString"]; 
string str = settings.ConnectionString; 
//第三种获取连接字符串的方法 
XmlDocument doc = new XmlDocument(); 
doc.Load("..//..//App.config"); 
XmlNode root = doc.SelectSingleNode("configuration"); 
XmlNode node = root.SelectSingleNode("connectionStrings/add[@name=’ConnectionString’]"); 
XmlElement el = node as XmlElement; 
string str = el.GetAttribute("connectionString"); 
//在程序中设置连接字符串 
connset.ConnectionString = "Data Source=orcl;Persist Security Info=True;User ID=xhfoc;Password=foc;Unicode=True"; 
connset.Save(); 
使用这种方法要修改Properties命名空间下的Settings.settings.cs文件,添加下面的代码: 
[global::System.Configuration.ApplicationScopedSettingAttribute()] 
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)] 
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=orcl;Persist Security Info=True;User ID=xhfoc;Password=foc;Unicode=True")]
          
public string ConnectionString 

     get 
     { 
         return ((string)(this["ConnectionString"])); 
     } 
     set 
     { 
         this["ConnectionString"] = value; 
     } 

              
//修改配置文件的方法          
XmlDocument doc = new XmlDocument(); 
doc.Load("..//..//App.config"); 
XmlNode root = doc.SelectSingleNode("configuration"); 
XmlNode node = root.SelectSingleNode("connectionStrings/add[@name=’ConnectionString’]"); 
XmlElement el = node as XmlElement; 
el.SetAttribute("connectionString", "Data Source=orcl;Persist Security Info=True;User ID=xhfoc;Password=foc;Unicode=True"); 
doc.Save("..//..//App.config");
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页