read, write and save values in app.config file

public void ChangeConfigValue()
        {
            string filename = System.AppDomain.CurrentDomain.BaseDirectory + @"web.config";
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(filename);
            XmlNodeList nodeList = xmldoc.DocumentElement.ChildNodes;

            foreach (XmlElement element in nodeList)
            {
                if (element.Name.ToLower() == "appsettings")
                {
                    XmlNodeList node = element.ChildNodes;
                    if (node.Count > 0)
                    {
                        foreach (XmlElement el in node)
                        {
                            if (el.Attributes["key"].InnerText == "ConnectionString")
                            {                           
                                el.Attributes["value"].InnerText = "321";//write the value
                                string s= el.Attributes["value"].InnerText;//read the value
                                break;
                            }
                        }
                    }
                    break;
                }
            }
            xmldoc.Save(filename);
        }

No comments:

Post a Comment