How to Edit .NET Configuration Files Programatically

Words
706
Reading
4 min
Listen
Play
9y

What Will I Learn?

  • You will learn how to edit .NET configuration files programatically

Requirements

  • .Net Framework

Difficulty

  • Intermediate

How to Edit .NET Configuration Files Programatically

Many .NET developers are taking advantage of the fact that you can quite easily store many of an application's settings in .NET configuration files instead of hard coding them into the application's code. What surprises me is that most of these developers don't even realize that in addition to making it easy to access the values stored in these files, the .NET Framework also makes it quite easy to manipulate these values programatically.

Configuration Files (*.config)

The .config file that almost everyone is familiar with is Web.config. Most .NET applications have one and it's the file that is in charge of storing most of an application's settings. By default, the Web.config file contains a section called which can be used to store custom application settings. Ideal things to store here are paths to files the application uses, Web service URLs, or any other application-wide settings that you'd like to be able to change easily. Since this is by far the most popular location for this type of setting, it's also the area the majority of developers might be interested in editing programatically. Because of this fact, the code in this article focuses exclusively on editing the section. That being said, there's absolutely no reason you can't modify the code to edit any section of any .NET configuration file.

Permissions

Before I proceed, I would like to take a second and mention that in order to use the included code (or any code that manipulates .config files) you'll need to ensure that the identity the code is running under has permission to perform the appropriate actions on the files being manipulated. This means either running the script as a user with elevated privileges (the lesser of the two evils) or relaxing the permissions on the .config files you'll be editing (not recommended). I'm not going to cover adjusting the permissions since it's not really relevant to the topic at hand and the topic of .NET permissions has been covered extensively elsewhere.

I did take one step to help make things a little easier when it comes to permissions and security. If you look at the included Web.config file, you'll notice that I've used the "configSource" attribute to move the section out of Web.config and into its own file called appSettings.config. So it's not very original... at least you know what's in it!

Web.config:

<?xml version="1.0"?>
<configuration>
    <appSettings configSource="appSettings.config" />
    
    <connectionStrings />
    <system.web>
        <compilation debug="true" />
        <authentication mode="Windows" />
    </system.web>
    <system.codedom />
    <system.webServer />
</configuration>

appSettings.config:

<?xml version="1.0"?>
<appSettings>
    <add key="WelcomeMessage" value="Welcome to our site!!!" />
    <add key="ThankYouMessage" value="Thanks for visiting... please come back soon." />
    <add key="SourceSite" value="http://www.utopian.io/" />
</appSettings>

By moving the section we'll be editing into another file, it allows us to manage the permissions on it separately from our main Web.config file and provides a small bit of comfort that all our changes should be happening in the appSettings.config file. I've left the section in the Web.config file commented out (instead of deleting it altogether) just in case you want to switch back.

The Code

The code is actually relatively straight-forward. The key is that instead of using the now deprecated ConfigurationSettings.AppSettings class that was so popular in .NET, we need to use the ConfigurationManager class or WebConfigurationManager class instead. Take a look at the code below to see some examples of these objects in action.

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Configuration" %>
<script runat="server">

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        ' On the first run of the page we populate our DropDownList (DDL).
        If Not Page.IsPostBack Then
            ' Populate our DDL with the list of keys from the appSettings section
            ' of our Web.config (or related) file.
            ddlAppSettingKeys.DataSource = WebConfigurationManager.AppSettings.Keys
            ddlAppSettingKeys.DataBind()
        End If
    End Sub

    ' When the user chooses a different key from the DDL, we update the
    ' value of the textbox to display the key's related value.
    Protected Sub ddlAppSettingKeys_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        txtAppSettingValue.Text = WebConfigurationManager.AppSettings(ddlAppSettingKeys.SelectedValue)
    End Sub

    ' Update the setting with the entered value.
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim myWebAppConfig As Configuration
        Dim myAppSettings As AppSettingsSection

        myWebAppConfig = WebConfigurationManager.OpenWebConfiguration("~")
        myAppSettings = myWebAppConfig.GetSection("appSettings")
        myAppSettings.Settings(ddlAppSettingKeys.SelectedValue).Value = txtAppSettingValue.Text
        myWebAppConfig.Save()
    End Sub
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>AppSettings Editor</title>
</head>
<body>

<form id="myForm" runat="server">
<div>

    <p>
    The DropDownList contains the existing appSettings keys.
    When a key is selected, the associated value is displayed
    in the TextBox for editing.
    </p>
    <p>
    Edit appSetting:
    <asp:DropDownList ID="ddlAppSettingKeys" runat="server"
        AutoPostBack="True"
        OnSelectedIndexChanged="ddlAppSettingKeys_SelectedIndexChanged"
    />
    </p>
    <p>
    Value:
    <asp:TextBox ID="txtAppSettingValue" runat="server"
        Columns="40"
    />
    <asp:Button ID="btnSave" runat="server"
        Text="Save Changes"
        OnClick="btnSave_Click"
    />
    </p>

    <br />

</div>
</form>

</body>
</html>

Here's a screen cap of the script in action:

alt

AppSettings Editor

It's got my usual plain-vanilla UI to keep things as uncluttered and readable as possible, but you didn't read this tutorial in order to see another example of lackluster design... it's all about the code.

The zip file also contains a more advanced version that allows you to add and delete key/value pairs instead of just letting you edit existing ones.

Conclusion

I hope this tutorial has shown you just how easy it is to edit .NET configuration files programatically. While I focused on the section of the Web.config file, since that's what most of the people reading this tutorial will be interested in editing, the process is the same for any section. Make a backup of your .config file of choice and give it a try. All you've got to lose is the chore of editing them by hand.



Posted on Utopian.io - Rewarding Open Source Contributors

How to Edit .NET Configuration Files Programatically | Ecency