How to edit external web.config file?

I am trying to write a winform application that will be able to edit the web.config file of an installed web application. I read the methods of the ConfigurationManager and WebConfigurationManager class, but I'm not sure how I can open the web application configuration file and edit it.

I am looking for a method that does not require loading the configuration file as a regular XmlDocument, although I am ready to do this if this is the only option available.

Any advice would be appreciated.

+6
web-config winforms configuration
source share
4 answers

So, here is the answer, I have EXACTLY the same scenario. I wanted to write a winforms application so that ordinary users can update web.config. You have to go about configuring goofy ...

// the key of the setting string key = "MyKey"; // the new value you want to change the setting to string value = "This is my New Value!"; // the path to the web.config string path = @"C:\web.config"; // open your web.config, so far this is the ONLY way i've found to do this without it wanting a virtual directory or some nonsense // even "OpenExeConfiguration" will not work var config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = path }, ConfigurationUserLevel.None); // now that we have our config, grab the element out of the settings var element = config.AppSettings.Settings[key]; // it may be null if its not there already if (element == null) { // we'll handle it not being there by adding it with the new value config.AppSettings.Settings.Add(key, value); } else { // note: if you wanted to you could inspect the current value via element.Value // in this case, its already present, just update the value element.Value = value; } // save the config, minimal is key here if you dont want huge web.config bloat config.Save(ConfigurationSaveMode.Minimal, true); 

Here is an example of what he is doing

Before:

 <?xml version="1.0"?> <configuration> <appSettings> <add key="MyKey" value="OldValue" /> </appSettings> <connectionStrings> <add name="myConnString" connectionString="blah blah blah" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration> 

After:

 <?xml version="1.0"?> <configuration> <appSettings> <add key="MyKey" value="This is my New Value!" /> </appSettings> <connectionStrings> <add name="myConnString" connectionString="blah blah blah" providerName="System.Data.SqlClient" /> </connectionStrings> <system.web> <trust level="Full" /> <webControls clientScriptsLocation="/aspnet_client/{0}/{1}/" /> </system.web> </configuration> 

Just be careful if you give it the wrong path, it will simply create a configuration file for that path / file name. Basically, check the .Exists file first.

By the way, while you are on it, you can write a class that represents your settings in your web.config. When you do this, write your getters / setters to read / write settings in the web.config file. When this is done, you can add this class as a data source and drag the data controls onto your winform. This will give you a fully edited winform web.config editor that you can easily pull out in minutes. I have an example at work that I will post tomorrow.

Full-featured winforms solution

So, this is a relatively simple solution to write Gui for editing web.config, some may say that it is too complicated when the notebook works fine, but it works for me and my audience.

It basically works, as described above, I wrote a class in which there were configuration parameters that I wanted to use as properties. ctor opens the file from the path, and getters / setters pull data from the returned configuration object, and in the end it has a save method that writes it. With this class, I can add the class as a data source and drag and drop related controls onto winforms. From there, all you have to do is plug in a button that calls the save method in your class.

Configuration class

 using System.Configuration; // This is a representation of our web.config, we can change the properties and call save to save them public class WebConfigSettings { // This holds our configuration element so we dont have to reopen the file constantly private Configuration config; // given a path to a web.config, this ctor will init the class and open the config file so it can map the getters / setters to the values in the config public WebConfigSettings(string path) { // open the config via a method that we wrote, since we'll be opening it in more than 1 location this.config = this.OpenConfig(path); } // Read/Write property that maps to a web.config setting public string MySetting { get { return this.Get("MySetting"); } set { this.Set("MySetting", value); } } // Read/Write property that maps to a web.config setting public string MySetting2 { get { return this.Get("MySetting2"); } set { this.Set("MySetting2", value); } } // helper method to get the value of a given key private string Get(string key) { var element = config.AppSettings.Settings[key]; // it may be null if its not there already if (element == null) { // we'll handle it not being there by adding it with the new value config.AppSettings.Settings.Add(key, ""); // pull the element again so we can set it below element = config.AppSettings.Settings[key]; } return element.Value; } // helper method to set the value of a given key private void Set(string key, string value) { // now that we have our config, grab the element out of the settings var element = this.config.AppSettings.Settings[key]; // it may be null if its not there already if (element == null) { // we'll handle it not being there by adding it with the new value config.AppSettings.Settings.Add(key, value); } else { // in this case, its already present, just update the value element.Value = value; } } // Writes all the values to the config file public void Save() { // save the config, minimal is key here if you dont want huge web.config bloat this.config.Save(ConfigurationSaveMode.Minimal, true); } public void SaveAs(string newPath) { this.config.SaveAs(path, ConfigurationSaveMode.Minimal, true); // due to some weird .net issue, you have to null the config out after you SaveAs it because next time you try to save, it will error this.config = null; this.config = this.OpenConfig(newPath); } // where the magic happens, we'll open the config here protected Configuration OpenConfig(string path) { return ConfigurationManager.OpenMappedExeConfiguration( new ExeConfigurationFileMap() { ExeConfigFilename = path }, ConfigurationUserLevel.None); } } 

Build, and then from there you can simply go to your winform design, go to Data> Show Data Sources (Shift + Alt + D). Right click> Add New Data Source and add it as an object as shown

Data Source Configuration Wizard 1 of 2 http://img109.imageshack.us/img109/8268/98868932.png

Data Source Configuration Wizard 2 of 2 http://img714.imageshack.us/img714/7287/91962513.png

Drag it (WebConfigSettings, topmost) onto winform. In my case, I will delete the navigator, as it is for the list, and I have it.

Recently Added Data Controls http://img96.imageshack.us/img96/8268/29648681.png

You should have something like webConfigSettingsBindingSource at the bottom of the constructor (shown in the following figure). Go to the code view and change ctor to

 public Form1() { InitializeComponent(); // wire up the actual source of data this.webConfigSettingsBindingSource.DataSource = new WebConfigSettings(@"c:\web.config"); } 

Add save button to your winform

Added save button http://img402.imageshack.us/img402/8634/73975062.png

Add the following event handler

 private void saveButton_Click(object sender, EventArgs e) { // get our WebConfigSettings object out of the datasource to do some save'n var settings = (WebConfigSettings)this.webConfigSettingsBindingSource.DataSource; // call save, this will write the changes to the file via the ConfigurationManager settings.Save(); } 

There, you now have a simple, simple web.config data editor. To add / remove fields, you simply change your WebConfigSettings class, update the data source in the "Data Sources" window (after assembly), and then drag n to remove new fields in the user interface.

You still have to include some code that indicates the opening of web.config, for this example I just encoded the path.

The nice thing is all that adds a graphical interface. You can easily add directory or file dialogs, you can have connection string testers, etc. Everything is very easy to add and very powerful for the end user.

+7
source share

I highly recommend you use XElement along with LINQ enabled (LINQ to XML).

For example, you want to change connectionString . This type of code is good enough

 var connString = from c in webConfigXElement.appSettings.connectionString where c.name == "myConnection" select c; 

and now you have full control over the <connectionString /> element and do whatever you want to do with it.

I turn to MSDN for training, as well as Get Started up for instant work.

Hope this helps you take full control of your .xml without pain.

+1
source share

Here you go, I wrote a toy application (VB.NET Windows client) that edits XML files using Tree / Grid for navigation and editing.

You can get some ideas from him. The VS project file for it here or only the MSI for installing it here if you want to try it on web.config.

It loads the file into a DataSet (DataSet.ReadXML ()), which parses it into DataTables, then displays and allows editing the contents in a standard DataGrid. Then it will save the edited content back to the XML file (DataSet.WriteXML ()).

0
source share

All app.config and web.config are just XML files. You can open and edit them using XMLDocument, XMLWriter, etc.

-one
source share

All Articles