ASP.NET Secrets, Part 3

The Best Place to Store Your Settings

Many Web developers end up storing important pieces of data—database connection strings, passwords, default settings—as troublesome constants. The problem with this is that they're difficult to edit: The slightest of changes means a complete recompile.

However, with ASP.NET, there is an easier way. It's likely you're well aware of the Web.config file, which stores settings for your applications, such as the session state timeout and authentication mode. It can also hold your own settings.

Here, I've added a key called "serverName" containing a value of "diomedes". You can list as many values here as you like: just keep adding <add> elements. And how do you read the value in your code? Simply reference the AppSettings collection of the System.Configuration.ConfigurationSettings class, as so:

And don't forget: Web.config is just an XML file and easily editable without a recompile. You could even use a third-party control, such as the free Web.config Editor from Hunterstone, to simplify all your administration. Easy!