Thursday, March 03, 2005

Overriding web.config app settings with user.config

Some time ago, I was in a situation where I wanted to set local application settings for a web application I was developing to some alternatives without messing with the project's copy of the web.config file. So I'd change my local copy by making it writable (normally the file was read-only because it is under source control). Every time I'd get latest version for the project it would either overwrite the file (if I forgot to leave the local copy) or I'd have to merge any changes manually.

Then I came up with this clever idea to have a little change script which would tickle the XML nodes of the web config file so I could just run that every time I got latest version. But it still was a pain because I had to remember to perform this action or it was more difficult to maintain.

Well, I just learned that .NET has a built in solution (that wasn't very well publicized apparently). Apparently, you can place the attribute [file="user.config"] in the web.config file and it will point to that file for application setting overrides. So you could then create that file in the application directory to hold your personal overrides for the default app settings. The file should look like this:

<add key="key" value="value" />

Note that 'appSettings' is the root node. The user.config file does not have to exist. .NET will just ignore a missing file and use the default values in web.config.

If you do create this file make sure you do not put it into the project (and, thus, source control) so as to avoid overwriting individual's settings.

I found this in the MSDN article: Team Development with Visual Studio NET and Visual SourceSafe - Chapter 4: Managing Dependencies

There are lots of other details in there that are helpful to know if you are building software in a team environment.


Anonymous said...

Thanks for the insight to the user.config file, Peter!

Anonymous said...

It's a useful mechanism. Note that for it to work the ASP.NET worker process has to have read access to the file and the directory it is in, otherwise it ignores the file as if it were not there

Paul Taylor

Peter Lanoie said...

@Paul Taylor: Yes. I certainly does. Although, typically the config file would be in the same directory as the rest of the web app files so permissions shouldn't be a problem. However, from a file management point of view, I could see storing the file outside of the app somewhat useful.