kennedy

A blog for blog-haters, by a blog-hater


Writing to Config files and You 

Tags: All, Session 6

I was able to clean up my demo code to get it working.  My "path" to the customErrors section was the issue (since it's nested in the system.web section, we have to use a bit of XPath to reference it.  The following code corresponds to a SelectedIndexChanged event for a DropDownList, and changes the customErrors mode attribute based on the mode selected in the dropdown (assume On, Off and RemoteOnly in the DropDownList).
 
        Configuration c = WebConfigurationManager.OpenWebConfiguration(null);
        CustomErrorsSection ces = (CustomErrorsSection)c.GetSection("system.web/customErrors");
        if (ces != null)
        {
            ces.Mode = (CustomErrorsMode)Enum.Parse(typeof(CustomErrorsMode), DropDownList1.SelectedValue);
            //c.Sections.Remove("customErrors");
            //c.Sections.Add("customErrors", ces);
            c.Save();
            Response.Write("new mode: " + ces.Mode.ToString());
        }
        else
            Response.Write("issues ...");
 
First, we get a reference to the web.config file.  Then we call GetSection to get the customErrors section in the system.web section.  If it's not null, we change the mode (as an aside, the mode is an enumeration, so we have to parse the text equivalent of the current SelectedIndex value to convert it to the enumeration type before assigning it into the Mode property.  Removing then re-Adding the section is not required as we're modifying an attribute.  Then we just Save it. 
 
Posted by Stephen Kennedy on 28-Nov-07
0 Comments  |  Trackback Url  |  Link to this post | Bookmark this post with:        
 

Comments

Name

Url

Email

Comments