views:

45

answers:

2

I have an ASP.NET project which has already some custom fields in it's web.config file. I've added in it three more fields and used them in my changes, and it's working great.

But where it needs to be used, there aren't these thre fields in the web.config (this was expected, I've just added by hand for tests and developing).

How do I check the existance of fields in web.config, and in case of not finding it, how do I add it permanently to the web.config ?

Thank you

+1  A: 

you can do something like this to see if the key exists in the config:

bool KeyExists(string key)
{
    return (!(ConfigurationManager.AppSettings[key] == null));
}

For the other part of your question, you could probably add stuff through the WebConfigurationManager class.

Edit: I generally save stuff in a database rather than a configuration file if the potential exists to add stuff dynamically, but that's just me.

jaltiere
I do that too, indeed. Though in this particular case I have to use web.config. Thank you!
MarceloRamires
How are you publishing your website? I would think that putting these keys in your development web.config would push them to your site so they are available at the first run of the website.
jaltiere
A: 

BE CAREFUL! I'm not entirely sure if the ASP.NET process even has permissions to change its web.config file, but if it does, rember that making this change will in effect restart the site and drop any existing sessions on the site.

Why, exactly, do you want to do this programmaticly? When you deploy your new code that uses these fields, why don't you swap out the existing web.config file with one containing your new fields?

MrGumbe
Because The web.config file is generated automatically, right ? and by deleting and re-installing the webstite the web.config file will be crated withouth these three fields, as far as I could tell. Having to replace the web.config file isn't quite desirable. The utimate question is: why do the currently-in-use custom fields in web.config appear in the first run of the website ? that's what I want.
MarceloRamires