How to save changes to a web.config section?

  • Thread starter Thread starter keithb
  • Start date Start date
K

keithb

How can an application change settings in the web.config file? I need to
allow users to configure SMTP email settings with functionality similar to
that provided developers by the ASP.NET Web Site Administration Tool. I
believe that I can get the settings using ConfigurationManager.GetSection,
but how can I save changes? If I do find a way to save changes, how can I
get IIS to read the file again so that the changes become immediately
available to the web site?

Thanks,

Keith
 
Hi Keith,

You're in luck because ASP.NET 2.0's Web Admin application does all this and
the source code is included. Take a look here:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ASP.NETWebAdminFiles\AppConfig

Also, check out the Save method here:

http://msdn2.microsoft.com/en-us/library/system.configuration.configuration.save(VS.80).aspx

Ken
Microsoft MVP [ASP.NET]


public void SaveConfig(Configuration config) {
RemotingManager.ShutdownTargetApplication();
config.NamespaceDeclared = true;

// check if session expired
if (String.IsNullOrEmpty(ApplicationPath) ||
String.IsNullOrEmpty((string)Session[APP_PHYSICAL_PATH])) {
Server.Transfer("~/home2.aspx");
}

config.Save(ConfigurationSaveMode.Minimal);
}
 
As for the second question, IIS resets the application as soon as there's a
change to the web.config.

Ken
 
How can an application change settings in the web.config file?

There's lots of ways, such as simply reading and writing your changes via
file classes, to reading the file into a XMLDom object, making changes, and
saving it again.

However, you should be VERY careful about this, since changing the
web.config file will cause any currently running application (including the
one you're making the changes in) to reset, losing things like session
variables, authentication, the currently state, etc.. Basically, you will
dump the user out of the website entirely, as well as every other user
currently on the site.

If that's not what you want, then you might need to look at other ways of
storing your data that needs changing.
 
If you want your changes to be immediately available after being written
without having the web application restart on you, then you'll need to wite
them either to an xml file or preferably to a database.

You can have a method in your configuration class's code that automatically
re-reads the data from the database (or file) whenever a change is made.

IIS doesn't read web.config files - the ASP.NET runtime does.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top