How to save configurations into web.config file?
I'm using a Asp.net dynamic web site application and can't save configurations into web.config file.
I have tried something like this, but doesn't work!
var configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
configuration.AppSettings.Settings["Value"].Value = "Some value";
configuration.开发者_Python百科Save();
Error I have got with
1. OpenWebConfiguration(Server.MapPath(".")) & OpenWebConfiguration(Server.MapPath("~"):
The relative virtual path 'C:/...' is not allowed here.
2. OpenWebConfiguration("~")
An error occurred loading a configuration file: Failed to map the path '/'.
I really don't know what to do anymore.
From the documentation it states that passing a null value for the path will open the default web.config file.
Looking at your code it doesn't appear that you are actually specifying a config filename in your path.
So use:
OpenWebConfiguration(null)
EDIT: O.k. I have done some further investigation and passing in null will access the servers default web.config file in the C:\Windows\Microsoft.NET\Framework\v2.0.50727\Config folder which is not what you want in this case.
Passing "~" should give you access to the web applications default web.config file and I have tested this successfully in Visual Studio 2008 with .NET 3.5 using the following code:
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
config.AppSettings.Settings["test"].Value = "Hello";
config.Save();
I am not sure why this is not working your case. I would suggest placing a breakpoint at the line of code where you create your Configuration object and use the "Immediate Window" in the Visual Studio IDE to call the WebConfigurationManager's static OpenWebConfiguration method to see what result you can get. Entering something like WebConfigurationManager.OpenWebConfiguration("~").AppSettings.Settings.AllKeys
should indicate if you are accessing your web.config successfully.
Use below code.
configuration.Save(ConfigurationSaveMode.Full, true);
精彩评论