명령 줄 매개 변수에서 .NET 애플리케이션 구성 파일을 선택하려면 어떻게합니까?

StackOverflow https://stackoverflow.com/questions/163803

문제

명령 줄 매개 변수를 전달하여 표준 app.config의 사용을 무시하고 싶습니다. configurationManager.AppSetting에 액세스 할 때 기본 응용 프로그램 구성 파일을 변경하려면 명령 줄에 지정된 구성 파일에 액세스 할 수 있습니까?

편집하다:

Exe Plus .config의 이름과 다른 구성 파일을로드하는 올바른 방법은 OpenMappedExeConfiguration을 사용하는 것입니다. 예를 들어

ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, "Shell2.exe.config");
currentConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None);

이것은 부분적으로 작동합니다. AppSettings 섹션의 모든 키를 볼 수 있지만 모든 값은 NULL입니다.

도움이 되었습니까?

해결책

따라서 실제로 기본값 이외의 구성 파일에서 AppSettings 섹션에 실제로 액세스 할 수있는 코드가 있습니다.

ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, "Alternate.config");
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None);

AppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings");
string MySetting = section.Settings["MySetting"].Value;

다른 팁

원하는 구성 파일을 AppName.exe.config에 복사 한 다음 AppName.exe를 실행하는 배치 파일.

나는 내 앱을 위해 이것을해야했고, 표준 구성 객체를 다루는 것은이 경로를 갔던 간단한 개념에 대해 괴물 같은 번거로 바뀌었다.

  1. App.Config와 유사한 여러 구성 파일을 XML 형식으로 유지합니다.
  2. 지정된 구성 파일을 a에로드하십시오 데이터 세트 (.readxml을 통해), 데이터 가능 config info가 내게 구성 객체.
  3. 그래서 내 모든 코드는 단지 구성 데이터 가능 값을 검색하고 그 크랩 타이치로 난독 화 된 앱 구성 객체가 아닙니다.

그런 다음 명령 줄에 필요한 구성 파일 이름을 전달할 수 있으며 하나가 없으면 app.config로로드합니다. 데이터 세트.

jeezus 그 후에는 훨씬 간단했습니다. :-)

이것은 기본 구성을 사용하고 명령 줄을 통해 재정의를 허용하는 앱 소스의 관련 부분입니다.

구성 객체로 현재 또는 사용자 구성을 가져옵니다

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string defCfgName = Environment.GetCommandLineArgs()[0] + ".config";

if (arg.Length != 0)
{
    string ConfigFileName = arg[0];
    if (!File.Exists(ConfigFileName))
        Fatal("File doesn't exist: " + ConfigFileName, -1);                
    config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = ConfigFileName }, ConfigurationUserLevel.None);
}
else if (!File.Exists(defCfgName)) Fatal("Default configuration file doesn't exist and no override is set." , -1);

구성 객체를 사용하십시오

AppSettingsSection s = (AppSettingsSection)config.GetSection("appSettings");
KeyValueConfigurationCollection a = s.Settings;
ConnectionString = a["ConnectionString"].Value;

이것은 정확히 당신이 원하는 것이 아닙니다 ... 실제를 리디렉션하기 위해 ConfigurationManager 다른 경로를 가리키는 정적 물체. 그러나 나는 그것이 당신의 문제에 대한 올바른 해결책이라고 생각합니다. 확인하십시오 OpenExeConfiguration 방법에 대한 방법 ConfigurationManager 수업.

위의 방법이 당신이 찾고있는 것이 아니라면 나는 또한 사용을 살펴볼 가치가 있다고 생각합니다. 구성 기능 Enterprise Library 프레임 워크 (Microsoft Patterns & Practices Team에서 개발 및 유지 관리).

구체적으로 FileConfigurationSource 수업.

다음은 FileConfigurationSource ~에서 엔터프라이즈 라이브러리, 나는 이것이 당신의 목표를 완전히 충족한다고 믿는다. 이것에 대해 Ent Lib에서 필요한 유일한 어셈블리는 Microsoft.Practices.EnterpriseLibrary.Common.dll.

static void Main(string[] args)
{
    //read from current app.config as default
    AppSettingsSection ass = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings;

    //if args[0] is a valid file path assume it's a config for this example and attempt to load
    if (args.Length > 0 && File.Exists(args[0]))
    {
        //using FileConfigurationSource from Enterprise Library
        FileConfigurationSource fcs = new FileConfigurationSource(args[0]);
        ass = (AppSettingsSection) fcs.GetSection("appSettings");
    }

    //print value from configuration
    Console.WriteLine(ass.Settings["test"].Value);
    Console.ReadLine(); //pause
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top