2010-10-05 69 views
2

我在我的web.config文件的AppSettings部分有一堆鍵。我想使用XML閱讀器技術閱讀這些應用程序設置的關鍵和值,並將它們填充到列表框中。使用XMl讀取器讀取配置文件

+3

你能做到這一點,但它會更容易簡單地用一個配置管理器,並通過所有的應用程序設置鍵遍歷。或者使用屬性文件並將它們全部放在一個類中。 – Justin 2010-10-05 22:22:49

回答

9

最好的方法是檢索webconfig值是使用System.Configuration.ConfigurationManager.AppSettings;

從XML閱讀器retrive webconfig值:

private void loadConfig() 
     { 

      XmlDocument xdoc = new XmlDocument(); 
      xdoc.Load(Server.MapPath("~/") + "web.config"); 
      XmlNode xnodes = xdoc.SelectSingleNode ("/configuration/appSettings"); 

       foreach (XmlNode xnn in xnodes .ChildNodes) 
       { 
        ListBox1.Items.Add(xnn.Attributes[0].Value + " = " + xnn.Attributes[1].Value); 
       }    

     } 

參考:http://dotnetacademy.blogspot.com/2010/10/read-config-file-using-xml-reader.html

+0

這種方式比ConfigurationManager.AppSettings更好,因爲你可以有任何你想要的文件名和路徑。 – 2017-06-20 10:37:55

2

你可以得到的AppSettings的NameValueCollection中的引用並重復如下:

NameValueCollection settings = System.Configuration.ConfigurationManager.AppSettings; 

foreach (string key in settings.AllKeys) 
{ 
    string value = settings[key]; 
} 

享受!

+0

非常感謝你們的幫助。它爲我工作。我也想保存值到配置文件有無論如何,我可以做到這一點 – user428747 2010-10-06 18:27:55

+0

看看這個帖子,否則你可以創建一個自定義配置節並保存。 http://stackoverflow.com/questions/453161/best-pratice-to-save-application-settings-in-windows-application – Doug 2010-10-06 20:35:25