Share via


HOW TO:從 Web.config 檔案讀取應用程式設定

更新:2007 年 11 月

這個範例會從 Web.config 檔讀取索引鍵 customsetting1 所識別的應用程式設定。appSettings 項目是字串的 NameValueCollection 集合。使用集合項目會比使用其他組態項目要複雜一些。

為了取得根目錄層級 Web 組態的組態設定,會將 null 傳遞給 OpenWebConfiguration 方法。

若要更新組態設定,請使用組態物件的 SaveSaveAs 方法。如需詳細資訊,請參閱使用組態類別。如需其他程式碼範例,請參閱 AppSettingsSection 類別和相關類別。

這個範例會使用非靜態的方法取得組態資料,可以讓您從任何應用程式擷取組態資料。如果您要從程式碼所在的應用程式中取得組態資訊,請使用靜態方法,這樣會較快處理。如需詳細資訊,請參閱 ASP.NET 組態 API 概觀中的<使用本機和遠端組態設定>章節。

範例

Dim rootWebConfig1 As System.Configuration.Configuration
rootWebConfig1 = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Nothing)
If (0 < rootWebConfig1.AppSettings.Settings.Count) Then
    Dim customSetting As System.Configuration.KeyValueConfigurationElement
    customSetting = rootWebConfig1.AppSettings.Settings("customsetting1")
    If Not (Nothing = customSetting.Value) Then
        Console.WriteLine("customsetting1 application string = {0}", customSetting.Value)
    Else
        Console.WriteLine("No customsetting1 application string")
    End If
End If
         System.Configuration.Configuration rootWebConfig1 =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
            if (0 < rootWebConfig1.AppSettings.Settings.Count)
            {
                System.Configuration.KeyValueConfigurationElement customSetting = 
                    rootWebConfig1.AppSettings.Settings["customsetting1"];
                if (null != customSetting)
                    Console.WriteLine("customsetting1 application string = \"{0}\"", 
                        customSetting.Value);
                else
                    Console.WriteLine("No customsetting1 application string");
            }

編譯程式碼

這項範例需要:

  • 根目錄 Web.config 檔中的 appSettings 項目,類似下列所示:

    <appSettings>
      <add key="customsetting1" value="Some text here"/>
    </appSettings>
    

    appSettings 項目是 <configuration> 項目的直接子系,並且是 system.web 項目的對等項目。

穩固程式設計

從 Web.config 檔之 appSettings 項目讀取的值一定屬於 String 型別。如果 Web.config 檔案中沒有指定的索引鍵,則不會發生錯誤,而是會傳回空字串。

安全性

應使用 Windows 安全性設定來限制可以讀取組態檔的對象,以保護伺服器上的組態檔。避免在 Web.config 檔的 appSettings 項目中存放機密的資訊,例如,使用者認證。同時考慮加密組態設定。如需詳細資訊,請參閱使用受保護的組態加密組態資訊

請參閱

參考

appSettings 項目 (一般設定結構描述)

ConfigurationSettings