Program Club

ConfigurationManager.AppSettings-수정 및 저장 방법

proclub 2020. 10. 22. 23:42
반응형

ConfigurationManager.AppSettings-수정 및 저장 방법


물어보기에는 너무 사소하게 들릴 수 있으며 기사에서 제안한 것과 동일한 작업을 수행하지만 예상대로 작동하지 않습니다. 누군가가 나를 올바른 방향으로 안내 할 수 있기를 바랍니다.

AppSettings별로 사용자 설정을 저장하고 싶습니다.

Winform이 닫히면 다음을 트리거합니다.

conf.Configuration config = 
           ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

if (ConfigurationManager.AppSettings["IntegrateWithPerforce"] != null)
    ConfigurationManager.AppSettings["IntegrateWithPerforce"] = 
                                           e.Payload.IntegrateCheckBox.ToString();
else
    config.AppSettings.Settings.Add("IntegrateWithPerforce", 
                                          e.Payload.IntegrateCheckBox.ToString());

config.Save(ConfigurationSaveMode.Modified);

따라서 항목이 아직 존재하지 않을 때 처음에는 단순히 작성하고 그렇지 않으면 기존 항목을 수정합니다. 그러나 이것은 저장되지 않습니다.

1) 내가 뭘 잘못하고 있니?

2) 앱 설정에 대한 사용자 설정이 다시 저장 될 것으로 예상하는 곳은 어디입니까? 디버그 폴더 또는 C : \ Documents and Settings \ USERNAME \ Local Settings \ Application Data 폴더에 있습니까?


설정 파일 추가를 살펴 봐야 할 것입니다. (예 : App.Settings)이 파일을 생성하면 다음을 수행 할 수 있습니다.

string mysetting = App.Default.MySetting;
App.Default.MySetting = "my new setting";

즉, 항목이 강력하게 입력 된 항목을 편집 한 다음 변경할 수 있으며 무엇보다도 배포하기 전에 xml을 만질 필요가 없습니다!

결과는 응용 프로그램 또는 사용자 컨텍스트 설정입니다.

설정 파일의 "새 항목 추가"메뉴를보십시오.


app.config 파일의 appSettings 섹션에서 값을 변경하는 방법 :

config.AppSettings.Settings.Remove(key);
config.AppSettings.Settings.Add(key, value);

일을합니다.

물론 더 나은 연습은 설정 클래스이지만 당신이 무엇을 추구하는지에 달려 있습니다.


나는 내가 늦었다는 것을 안다. :) 그러나 이것은 내가 그것을하는 방법 :

public static void AddOrUpdateAppSettings(string key, string value)
{
    try
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }
}

자세한 내용은 MSDN을 참조하십시오.


섹션을 선호 <appSettings>합니다 <customUserSetting>. (Web) ConfigurationManager로 읽고 쓰는 것이 훨씬 쉽습니다. ConfigurationSection, ConfigurationElement 및 ConfigurationElementCollection을 사용하려면 사용자 지정 클래스를 파생하고 사용자 지정 ConfigurationProperty 속성을 구현해야합니다. 단순한 일상의 필사자 IMO에게는 너무 많은 방법입니다.

다음은 web.config를 읽고 쓰는 예입니다.

using System.Web.Configuration;
using System.Configuration;

Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
string oldValue = config.AppSettings.Settings["SomeKey"].Value;
config.AppSettings.Settings["SomeKey"].Value = "NewValue";
config.Save(ConfigurationSaveMode.Modified);

전에:

<appSettings>
  <add key="SomeKey" value="oldValue" />
</appSettings>

후:

<appSettings>
  <add key="SomeKey" value="newValue" />
</appSettings>

기본 질문은 win 양식에 관한 것이므로 여기에 해결책이 있습니다. (방금 user1032413에 의해 코드를 windowsForms 설정을 rflect하도록 변경했습니다) 새 키인 경우 :

Configuration config = configurationManager.OpenExeConfiguration(Application.ExecutablePath); 
config.AppSettings.Settings.Add("Key","Value");
config.Save(ConfigurationSaveMode.Modified);

키가 이미있는 경우 :

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); 
config.AppSettings.Settings["Key"].Value="Value";
config.Save(ConfigurationSaveMode.Modified);

저장 호출 후에 이것을 추가하십시오.

ConfigurationManager.RefreshSection( "appSettings" );

ConfigurationManager는 시작 프로젝트에있는 app.config를 하나만 사용합니다.

If you put some app.config to a solution A and make a reference to it from another solution B then if you run B, app.config from A will be ignored.

So for example unit test project should have their own app.config.


I think the problem is that in the debug visual studio don't use the normal exeName.

it use indtead "NameApplication".host.exe

so the name of the config file is "NameApplication".host.exe.config and not "NameApplication".exe.config

and after the application close - it return to the back app.config

so if you check the wrong file or you check on the wrong time you will see that nothing changed.


You can change it manually:

private void UpdateConfigFile(string appConfigPath, string key, string value)
{
     var appConfigContent = File.ReadAllText(appConfigPath);
     var searchedString = $"<add key=\"{key}\" value=\"";
     var index = appConfigContent.IndexOf(searchedString) + searchedString.Length;
     var currentValue = appConfigContent.Substring(index, appConfigContent.IndexOf("\"", index) - index);
     var newContent = appConfigContent.Replace($"{searchedString}{currentValue}\"", $"{searchedString}{newValue}\"");
     File.WriteAllText(appConfigPath, newContent);
}

참고URL : https://stackoverflow.com/questions/5274829/configurationmanager-appsettings-how-to-modify-and-save

반응형