How to save configurations into web.config file?

旧城冷巷雨未停 提交于 2019-12-12 18:38:43

问题


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.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.


回答1:


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.




回答2:


Use below code.

configuration.Save(ConfigurationSaveMode.Full, true);


来源:https://stackoverflow.com/questions/4134162/how-to-save-configurations-into-web-config-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!