读取和写入配置文件内容的方法

读取和写入配置文件内容的方法

1  读取 <connectionStrings>  根下面   name 里面的connectionString 值

读取和写入配置文件内容的方法
//读取 
 public static string url = ConfigurationManager.ConnectionStrings["url"].ConnectionString;

//写入 的方法 

  public static void Savedd(string conn, string name)
        {
            XmlDocument doc = new XmlDocument();
            string strFileName = Application.ExecutablePath + ".config";
            doc.Load(strFileName);
            XmlNodeList nodes = doc.GetElementsByTagName("add");
            for (int i = 0; i < nodes.Count; i++)
            {
                XmlAttribute att = nodes[i].Attributes["name"];
                if (att.Value == name)
                {
                    att = nodes[i].Attributes["connectionString"];
                    att.Value = conn;
                    break;
                }
            }
            doc.Save(strFileName);
        }
读取和写入配置文件内容的方法

2 . 读取   <appSettings>  里面 key 的值

读取和写入配置文件内容的方法
   /// <summary>
        /// 写入key值
        /// </summary>
        public static bool SetKeyValue(string key, string value)
        {
            //增加的内容写在appSettings段下 <add key="RegCode" value="0"/>
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            try
            {
                if (config.AppSettings.Settings[key] == null)
                {
                    config.AppSettings.Settings.Add(key, value);
                }
                else
                {
                    config.AppSettings.Settings[key].Value = value;
                }
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }

读取 
  public static string ip = ConfigurationManager.AppSettings["ip"];//