나는 두 세계의 장점을 원합니다. 사용자 범위 응용 프로그램 설정과 같이 런타임 중에 변경 사항을 유지할 수 있기를 원하며이 설정을 전역으로 유지하려고합니다. app.config 설정 파일을 통해이를 수행 할 수있는 방법이 있습니까? 내 애플리케이션의 런타임 편집 가능 설정을 전역으로 유지하는 다른 방법을 찾아야합니까?C# .NET의 전역 편집 가능 구성 설정?
답변
확인에 대한 몇 가지 정보가입니다
는, 이것은 내가 그것을 해결하는 방법입니다 구성 파일 관리 :
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>
과 같은
구성 파일의 응용 프로그램 설정을 처리하는 데 사용되는 .Net의 기본 구성 관리자는 읽기 전용이므로 기술적으로 기본 라이브러리를 사용하여 구성 할 수는 없지만 구성 파일은 xml 의, 당신은 단지 표준 XML 방법을 사용하여 구성 파일을 업데이트하고,
또한 설정 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
, ConfigurationElement
및 ConfigurationElementCollection
구현을 만든 : 여기 OpenMappedExeConfiguration
- 1. C# .net의 전역 변수
- 2. C#/NET의 가변 문자열 편집
- 3. JCombobox 편집 가능 가능
- 4. jquery 편집 가능 링크 편집?
- 5. .NET의 사용자 설정
- 6. "편집 가능"내 gridview에서
- 7. .net의 스크립트 기반 구성?
- 8. xpath를 사용하여 편집 가능
- 9. jQuery 편집 가능/정렬 가능 목록
- 10. .net의 Windows 구성 요소
- 11. .NET의 공유 구성 파일
- 12. 푹신한 클라우드 구성 .NET의 경우
- 13. jQuery의 전역 변수 설정
- 14. 스레드의 전역 변수 설정
- 15. PHP 전역 경로 설정
- 16. PHP의 관리자 페이지에서 구성 할 수있는 전역 설정 저장
- 17. Magento 속성을 Soap API를 사용하여 구성 가능 제품으로 설정
- 18. 편집 가능 및 편집 불가능 셀이있는 Dojo Grid
- 19. 각주를 처리하는 C++ 텍스트 편집 구성 요소?
- 20. JTable에서 한 행만 편집 가능
- 21. MS 액세스의 편집 가능, 추가 가능 콤보 상자 (?)
- 22. C# WinForms 응용 프로그램에서 편집 가능한 구성 설정을 만들려면 어떻게해야합니까?
- 23. Windows 서비스 구성 설정
- 24. PHP - 상수/전역 변수/구성
- 25. 템플릿 태그에 전역 템플릿 변수 설정
- 26. QLabel에 대한 전역 위치 설정
- 27. 출력 읽기 전용, wx.textctrl로 입력 편집 가능?
- 28. 편집 PHP 설정 파일이
- 29. C# 응용 프로그램 및 구성 설정
- 30. 프로그래밍 방식으로 네트워크 구성 설정 C#