-1

I need help updating <appsettings> value in the Web.config, I keep getting the following error message:

A configuration file cannot be created for the requested Configuration object.

I've tried with ASP.NET Webform framework 4.0, 4.5, 4.6, 4.7 and neither one works

Here is my code:

protected void btnUpdate_Click(object sender, EventArgs e)
{
    try
    {
        var keyName = this.asetKeyName.Text.Trim();
        var keyValue = this.asetKeyValue.Text.Trim();
        var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/web.config");
        config.AppSettings.Settings[keyName].Value = keyValue;
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("web.config");
        this.lit_Content.Text = "Successfully Updated.";
    }
    catch (Exception exm)
    {
        this.lit_Content.Text = exm.Message.ToString();
        Console.WriteLine(exm.Message.ToString());
    }
}
0

1 Answer 1

-1

I think this is not possible to update the web config file in run time just by a click event. Because, this is a configration file which is self explanatory.

Most ASP.NET applications come with a prebuilt Web.config file that can be edited with any text editor such as Notepad. Generally, Web.config files contain comments that make editing the file self-explanatory. However, you may have to add configuration items to a Web.config file that doesn't already have the configuration item defined.

For a sample Web.config file like below:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="countoffiles" value="7" />
    <add key="logfilelocation" value="abc.txt" />
  </appSettings>
</configuration>

You'll need to add a reference to System.Configuration in your project's references folder.

You should definitely be using the ConfigurationManager over the obsolete ConfigurationSettings.

This is how to access the appSetting key:

string value = System.Configuration.ConfigurationManager.AppSettings["countoffiles"];
Sign up to request clarification or add additional context in comments.

3 Comments

Web apps don't use app.config, so you still need to improve it.
Thank you, Kumar, for your answer, but that does not work with WebForms, As Lex Li mentioned WEBFORM does not have appSetting, appSettings works on WINFORMS, it is sad that Microsoft never can get their programming language tools to work 100%, there is always a detour, that is why lots of developer do not trust MS tools.
Hi Lex and ALDiz, this should be Web.config, not the app.config. I have corrected.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.