
|
Editing .NET Configuration Files Programatically By John Peterson | |
Rating: 5 out of 5 Rate this article
|
email this article to a colleague
suggest an article
|
download source code
Introduction
These days, 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
<appSettings> 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 <appSettings> 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 <appSettings> 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" />
<!--
<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.15seconds.com/" />
</appSettings>
-->
<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.15seconds.com/" />
</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 <appSettings> 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 1.x, 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 /><br /><br />
<p style="font-size:smaller;">
This script was downloaded from <a href="http://www.15seconds.com/">15 Seconds</a>.
For more information about the code and it's usage, please check out the original article:
<a href="http://www.15seconds.com/issue/090912.htm">Editing .NET Configuration Files
Programatically</a>.
</p>
</div>
</form>
</body>
</html>
Here's a screen cap of the script in action:
It's got my usual plain-vanilla UI to keep things as uncluttered and readable as possible, but
you didn't read this article 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 article has shown you just how easy it is to edit .NET configuration files programatically.
While I focused on the <appSetting> section of the Web.config file,
since that's what most of the people reading this article 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.
|
|
|
|
|
|
|
Other Articles
|
|
|
|
|
Apr 28, 2005 - New Files and Folders in ASP.NET 2.0
|
|
|
With the release of ASP.NET 2.0, Microsoft has greatly increased the power of ASP.NET by introducing a suite of new features and functionalities. As part of this release, ASP.NET 2.0 also comes with a host of new special files and folders that are meant to be used to implement a specific functionality. This article examines these new files and folders in detail and provides examples that demonstrate how to utilize them to create ASP.NET 2.0 applications.
[Read This Article] [Top]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Dec 15, 2004 - A Sneak Peek at ASP.NET 2.0's Administrative Tools
|
|
|
With ASP.NET 2.0, Microsoft has made great strides in increasing developer productivity and has made implementing previously complex solutions relatively easy. Where this version of ASP.NET really shines, however, is in its new administrative tools that allow developers to spend less time managing the configuration of the servers and software and more time developing great code.
[Read This Article] [Top]
|
|
|
|
Nov 17, 2004 - The ASP.NET 2.0 TreeView Control
|
|
|
Thiru Thangarathinam introduces ASP.NET 2.0's new TreeView control which provides a seamless way to consume and display information from hierarchical data sources. The article discusses this new control in depth and explains how to use this feature rich control in your ASP.NET applications.
[Read This Article] [Top]
|
|
|
Mailing List
Want to receive email when the next article is published? Just Click Here to sign up.
|
|