C# Winform 修改app.config文件

阅读更多

xml version="1.0" encoding="utf-8" ?>
<configuration>
   
<connectionStrings>connectionStrings>
   
<appSettings>
       
<add key="Server" value=" "/>
       
<add key="initial catalog" value=" ">add>
       
<add key="uid" value=" ">add>
       
<add key="pwd" value=" ">add>
   
appSettings>
configuration>



#region  方法保存修改的设置
       
///


       
/// 方法保存修改的设置
       
///

       
///
       
///
        private void SaveConfig(string ConnenctionString, string strKey)
        {
            XmlDocument doc
= new XmlDocument();
           
//获得配置文件的全路径
            string strFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            doc.Load(strFileName);
           
//找出名称为“add”的所有元素
            XmlNodeList nodes = doc.GetElementsByTagName("add");
           
for (int i = 0; i < nodes.Count; i++)
            {
               
//获得将当前元素的key属性
                XmlAttribute att = nodes[i].Attributes["key"];
               
//根据元素的第一个属性来判断当前的元素是不是目标元素
                if (att.Value == strKey)
                {
                   
//对目标元素中的第二个属性赋值
                    att = nodes[i].Attributes["value"];
                    att.Value
= ConnenctionString;
                   
break;
                }
            }
           
//保存上面的修改
            doc.Save(strFileName);
        }
       
#endregion

//调用方法修改app.config文件
private void btnOK_Click_1(object sender, EventArgs e)
        {
                SaveConfig(
"WWW-8CB7FB23DD4","Server");
                SaveConfig(
"myehrce","initial catalog");
                SaveConfig(
"sa", "uid");
                SaveConfig(
"123","pwd");
        }

你可能感兴趣的:(C# Winform 修改app.config文件)