2011-05-09 4 views
1

나는 두 세계의 장점을 원합니다. 사용자 범위 응용 프로그램 설정과 같이 런타임 중에 변경 사항을 유지할 수 있기를 원하며이 설정을 전역으로 유지하려고합니다. app.config 설정 파일을 통해이를 수행 할 수있는 방법이 있습니까? 내 애플리케이션의 런타임 편집 가능 설정을 전역으로 유지하는 다른 방법을 찾아야합니까?C# .NET의 전역 편집 가능 구성 설정?

답변

0

확인에 대한 몇 가지 정보가입니다

, 이것은 내가 그것을 해결하는 방법입니다 구성 파일 관리 :

public static class Settings 
{ 
    private static string _root { get { return "core"; } } 

    private static Configuration Load() 
    { 
     string filename = Path.Combine(Core.BaseDirectory, "core.config"); 

     var mapping = new ExeConfigurationFileMap {ExeConfigFilename = filename}; 
     var config = ConfigurationManager.OpenMappedExeConfiguration(mapping, ConfigurationUserLevel.None); 

     var section = (CoreConfigurationSection)config.GetSection(_root); 

     if (section == null) 
     { 
      Console.Write("Core: Building core.config..."); 

      section = new CoreConfigurationSection(); 
      config.Sections.Add(_root, section); 
      Defaults(section); 
      config.Save(ConfigurationSaveMode.Modified); 

      Console.WriteLine("done"); 
     } 

     return config; 
    } 

    private static void Defaults(CoreConfigurationSection section) 
    { 
     section.Settings["Production"] = "false"; 
     section.Settings["Debug"] = "false"; 
     section.Settings["EventBot"] = "true"; 
     section.Settings["WebAccounting"] = "true"; 
     section.Settings["AllowPlayers"] = "true"; 
    } 

    #region Accessors 

    public static string Get(string setting) 
    { 
     var config = Load(); 
     var section = (CoreConfigurationSection)config.GetSection(_root); 

     return section.Settings[setting]; 
    } 

    public static bool GetBoolean(string setting) 
    { 
     var config = Load(); 
     var section = (CoreConfigurationSection)config.GetSection(_root); 

     return section.Settings[setting].ToLower() == "true"; 
    } 

    public static void Set(string setting,string value) 
    { 
     var config = Load(); 
     var section = (CoreConfigurationSection)config.GetSection(_root); 

     if (value == null) 
      section.Settings.Remove(setting); 

     section.Settings[setting] = value; 
     config.Save(ConfigurationSaveMode.Modified); 
    } 

    public static void SetBoolean(string setting, bool value) 
    { 
     var config = Load(); 
     var section = (CoreConfigurationSection)config.GetSection(_root); 

     section.Settings[setting] = value.ToString(); 
     config.Save(ConfigurationSaveMode.Modified); 
    } 

    #endregion 

    #region Named settings 

    public static bool Production 
    { 
     get { return GetBoolean("Production"); } 
     set { SetBoolean("Production", value); } 
    } 

    public static bool Debug 
    { 
     get { return GetBoolean("Debug"); } 
     set { SetBoolean("Debug", value); } 
    } 

    public static bool EventBot 
    { 
     get { return GetBoolean("EventBot"); } 
     set { SetBoolean("EventBot", value); } 
    } 

    public static bool WebAccounting 
    { 
     get { return GetBoolean("WebAccounting"); } 
     set { SetBoolean("WebAccounting", value); } 
    } 

    public static bool AllowPlayers 
    { 
     get { return GetBoolean("AllowPlayers"); } 
     set { SetBoolean("AllowPlayers", value); } 
    } 

    #endregion 
} 

하드 코딩보다 입력 된 구성을 만드는 더 좋은 방법을 생각할 수는 없지만 런타임시 구성을 만들고 업데이트 할 수 있고, 편집 가능하며 전역에 배치 할 수 있습니다. 내 응용 프로그램 루트, 그래서 기본적으로 내가 원하는 모든 기능을 다루고 있습니다.

core.config 파일은 런타임에 만들어지지 않습니다. 존재하지 않으면 설정을로드하거나 저장할 때마다 "시작"이라는 기본 값으로 확인됩니다. 그 생각 "초기화". core.config 파일이

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <configSections> 
     <section name="core" type="Server.CoreConfigurationSection, ServerCore, Version=2.1.4146.38077, Culture=neutral, PublicKeyToken=null" /> 
    </configSections> 
    <core> 
     <settings> 
      <setting name="Production" value="false" /> 
      <setting name="Debug" value="false" /> 
      <setting name="EventBot" value="true" /> 
      <setting name="WebAccounting" value="true" /> 
      <setting name="AllowPlayers" value="true" /> 
     </settings> 
    </core> 
</configuration> 
과 같은

1

구성 파일의 응용 프로그램 설정을 처리하는 데 사용되는 .Net의 기본 구성 관리자는 읽기 전용이므로 기술적으로 기본 라이브러리를 사용하여 구성 할 수는 없지만 구성 파일은 xml 의, 당신은 단지 표준 XML 방법을 사용하여 구성 파일을 업데이트하고,

0

또한 설정 OpenMappedExeConfiguration을 (다시로드 할 때 다음

ConfigurationManager.RefreshSection("appSettings") 

를 호출 할 수없는 이유가 없습니다 그래서) 방법 ConfigurationManager를 사용하면 선택한 구성 파일을 동적으로로드 할 수 있습니다 (.NET xml 구성 스키마에 따라 부여됨) 응용 프로그램에서 응용 프로그램 구성을로드하게하십시오. 따라서 @lomax가 으로 표시된 파일을 수정하면이 동일한 방법을 사용하여 모든 응용 프로그램에서로드 할 수있는 공통 파일을 가질 수 있습니다. 다음

public class CoreConfigurationSection : ConfigurationSection 
{ 
    [ConfigurationProperty("settings", IsDefaultCollection = true)] 
    [ConfigurationCollection(typeof(CoreSettingCollection), AddItemName = "setting")] 
    public CoreSettingCollection Settings 
    { 
     get 
     { 
      return (CoreSettingCollection)base["settings"]; 
     } 
    } 
} 

public class CoreSetting : ConfigurationElement 
{ 
    public CoreSetting() { } 

    public CoreSetting(string name, string value) 
    { 
     Name = name; 
     Value = value; 
    } 

    [ConfigurationProperty("name", IsRequired = true, IsKey = true)] 
    public string Name 
    { 
     get { return (string)this["name"]; } 
     set { this["name"] = value; } 
    } 

    [ConfigurationProperty("value", DefaultValue = null, IsRequired = true, IsKey = false)] 
    public string Value 
    { 
     get { return (string)this["value"]; } 
     set { this["value"] = value; } 
    } 
} 

public class CoreSettingCollection : ConfigurationElementCollection 
{ 
    public new string this[string name] 
    { 
     get { return BaseGet(name) == null ? string.Empty : ((CoreSetting)BaseGet(name)).Value; } 
     set { Remove(name); Add(name, value); } 
    } 

    public void Add(string name, string value) 
    { 
     if (!string.IsNullOrEmpty(value)) 
      BaseAdd(new CoreSetting(name, value)); 
    } 

    public void Remove(string name) 
    { 
     if (BaseGet(name) != null) 
      BaseRemove(name); 
    } 

    protected override ConfigurationElement CreateNewElement() 
    { 
     return new CoreSetting(); 
    } 

    protected override object GetElementKey(ConfigurationElement element) 
    { 
     return ((CoreSetting)element).Name; 
    } 
} 

그리고 클래스 :

난 정말 기본 ConfigurationSection, ConfigurationElementConfigurationElementCollection 구현을 만든 : 여기 OpenMappedExeConfiguration