2013-06-05 2 views
2

나는이 구성 파일이 있습니다구성 파일

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <appSettings> 
     <add key="AuxAppStg0" value="5 iunie 2013 19:22:49" /> 
     <add key="AuxAppStg1" value="5 iunie 2013 00:00:00" /> 
     <add key="AppStg2" value="5 iunie 2013 19:23:04" /> 
    </appSettings> 
</configuration> 

을 그리고 나는이 코드를 사용하여 분석 할 :

// Get the configuration file. 
     System.Configuration.Configuration config = 
      ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 

     // Get the appSettings section. 
     System.Configuration.AppSettingsSection appSettings = 
      (System.Configuration.AppSettingsSection)config.GetSection("appSettings"); 



     foreach (KeyValueConfigurationElement i in appSettings.Settings) 
     { 

      Console.WriteLine("Key: {0} Value: {1}", i.Key, i.Value); 
     } 

     if (appSettings.Settings.Count != 0) 
     { 
      foreach (string key in appSettings.Settings.AllKeys) 
      { 
       string value = appSettings.Settings[key].Value; 
       Console.WriteLine("Key: {0} Value: {1}", key, value); 
      } 
     } 
     else 
     { 
      Console.WriteLine("The appSettings section is empty. Write first."); 
     } 

을 내가 가진 전부입니다 : appSettings는 섹션입니다 빈. 먼저 작성하십시오. 찾았습니다. here입니다. 내가 뭘 잘못하고 있니? 시작시 읽을 수 있도록 C# Windows 서비스에 대한 구성 파일을 만들고 싶습니다.이 방법은 다른 방법보다 뛰어납니다.

+0

당신의 .config 파일의 이름은 무엇입니까 :

그럼 당신은 이런 식으로 뭔가를 사용할 수 있습니까? 마지막에 서비스 실행 파일명 + .config의 이름이어야하므로'MyWindowsService.exe'는'MyWindowsService.exe.config'이어야합니다. 또한 서비스 실행 파일과 동일한 디렉토리에 있어야합니다. 파일에 대한 변경 사항을 가져 오려면 Windows 서비스를 다시 시작해야합니다. – vcsjones

+6

왜 ConfigurationManager.AppSettings를 사용하지 않습니까? –

+0

@ matt-dot-net 잘 잡아라, +1. – vcsjones

답변

4

먼저 System.configuration 참조를 프로젝트에 가져와야합니다.

private void ParseAppSettings() { 
    string value = string.Empty; 
    foreach (string key in System.Configuration.ConfigurationManager.AppSettings.AllKeys) 
    { 
     value = System.Configuration.ConfigurationManager.AppSettings[key]; 
     Console.WriteLine("Key: {0} Value: {1}", key, value); 
    } 
}