I love .NET: Custom Web.Config sections with a WinForms application
We have a WinForms application at my company which is used to basically set up and configure a user's Web.Config file as part of the instalation process of our web software.
I'm currently going over it with a fine-toothed comb to make the interface and the flow of events a little nicer for the user.
One of the aspects of it I'm changing is to have a user-input SQL Server name and database name written back to the Web.Config file into a custom section of the configuration.
One problem - that doesn't work. Not through the built in/standard methods that .NET provides anyway.
The simple way of accessing section of the Web.Config should be as smooth as this:
CustomConfigSection myConfigSection = ConfigurationManager.GetSection("MyCustomSection") as CustomConfigSection;
This, whichever way you cut it, always returns null. There's a number of people on the web having the same issue, and the problem simply seems to be that a WinForms (or console for that matter) application does not like to deal with custom sections.
The quickest way I've found around this is to read out the Web.Config file as XML, make the changes to the required element, and save the file. It's a bit crude, but here's an example:
XmlDocument doc = new XmlDocument();
doc.Load("path/to/file.xml");
XmlNode myNode = doc.SelectSingleNode("//configuration/MyCustomSection");
myNode.Attributes["SomeAttribute"].Value = "SomeValue";
doc.Save("path/to/file.xml");
Hopefully this might help other people beating their heads against a wall trying to create custom this that and the other trying to get it working - and if anyone does actually have a solution, let me know.



Comments [1]