1. 程式人生 > >C#基本知識 -- App.config檔案的配置與讀取

C#基本知識 -- App.config檔案的配置與讀取

對於需要配置的常量,在App.config中進行配置,格式為:

<add key="變數名" value="變數值">如:

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <configuration>
  3.   <appSettings>
  4.     <addkey="SourceFolder"value="D:\CodeFolder\MysolutionTest"/>
  5.     <addkey="FindingString"value="要搜尋的字串"/>
  6.     <addkey="OutputFile"
    value="E:\test\result.txt"/>
  7.   </appSettings>
  8. </configuration>


在主程式中,需要讀取App.config檔案中配置的變數,採用
NameValueCollection appSettings = System.Configuration.ConfigurationManager.AppSettings;
來獲取各個變數名和變數值。如
NameValueCollection appSettings = System.Configuration.ConfigurationManager.AppSettings;
string path = appSettings["SourceFolder"];在主程式中,需要讀取App.config檔案中配置的變數,採用
NameValueCollection appSettings = System.Configuration.ConfigurationManager.AppSettings;
來獲取各個變數名和變數值。如

  1. NameValueCollection appSettings = System.Configuration.ConfigurationManager.AppSettings;  
  2. string path = appSettings["SourceFolder"];