简体   繁体   English

C#修改App.Config文件,

[英]C# Modify the App.Config File,

How to Modify the App.config file..! 如何修改App.config文件..! I was able to modify the key,value in the memory. 我能够修改内存中的键,值。 I need to modify it to the file..? 我需要将其修改为文件。 Is it possible? 可能吗?

private string UpdateSetting(string key, string value)
        {
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            configuration.AppSettings.Settings.Add(key, value);
            configuration.Save();
            ConfigurationManager.RefreshSection("appSettings");
            return null;
        }

this will change the value of the key in the memory, Can I modify it the File? 这将更改内存中密钥的值,我可以修改它的文件吗?

Your problem is in this line: 您的问题在这一行:

configuration.Save();

You should use 你应该用

configuration.Save(ConfigurationSaveMode.Modified);

Here is my own class for working with configurations: 这是我自己的关于配置的课程:

public class SettingsManager
{

    public static string ReadSetting(string key)
    {
        try
        {
            var appSettings = ConfigurationManager.AppSettings;
            var result = appSettings[key] ?? string.Empty;
            return result;
        }
        catch (ConfigurationErrorsException exc)
        {
            //Logger.WriteLog(exc.Message, LoggingLevel.Error);
        }
        return string.Empty;
    }

    public static void AddUpdateAppSettings(string key, string value)
    {
        try
        {
             var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
             var settings = configFile.AppSettings.Settings;
             if (settings.Count == 0 | settings[key] == null)
             {
                  settings.Add(key, value);
             }
             else
             {
                  settings[key].Value = value;
             }
             configFile.Save(ConfigurationSaveMode.Modified);             
             ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
        }
        catch (ConfigurationErrorsException exc)
        {
            //Logger.WriteLog(exc.Message, LoggingLevel.Error);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM