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");

 

本文转至:http://taiyangly.blog.163.com/blog/static/13711553420107294384318/

你可能感兴趣的:(C#)