2

I'm just reading the web.config file through this code as

Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");

AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");

if (appSettingsSection != null)
{
         appSettingsSection.Settings.Remove(key);
         config.Save();
}

It works fine when appSettings is present in the web.config file.

My query is to add appSettings tag in web.config file if it is not present.

2
  • typically you would simply edit the config file. why are you trying to modify it problematically? Commented Dec 5, 2012 at 13:55
  • @Jason Meckley its my work what to do Commented Dec 5, 2012 at 13:57

2 Answers 2

1

Here I am adding new application key "myKey" with value "myValue":

        System.Configuration.KeyValueConfigurationCollection settings;
        System.Configuration.Configuration config;

        System.Configuration.ExeConfigurationFileMap configFile = new System.Configuration.ExeConfigurationFileMap();
        configFile.ExeConfigFilename = "App.config";
        config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configFile, System.Configuration.ConfigurationUserLevel.None);
        settings = config.AppSettings.Settings;

        config.AppSettings.Settings.Add(new System.Configuration.KeyValueConfigurationElement("myKey", "myValue"));
        config.Save();

So the point is to load specific config (add appSettings in you wish), add new keys and save it.

Happy coding!

Sign up to request clarification or add additional context in comments.

Comments

0

You can check if your web.config has appSettings tag or not like this;

string s = ConfigurationManager.AppSettings["appSettings"];

if (!String.IsNullOrEmpty(s))
{
    // Key exists
}
else
{
    // Key doesn't exist
}

I couldn't find anything adding dynamically appSettings tag but found three-part series about .NET configuration that could be quite usefull.

1 Comment

its k how can we add appsettings tag to it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.