Share via


HOW TO:從 Web.config 檔案讀取連接字串

更新:2007 年 11 月

這個範例會從 Web.config 檔讀取連接字串 (Connection String)。connectionStrings 項目是 ConnectionStringSettings 物件的 ConnectionStringSettingsCollection 集合。使用集合項目會比使用其他組態項目要複雜一些。

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

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

注意事項:

這個範例適用於名為 MyWebSiteRoot 的網站。若要執行範例,必須在使用該名稱的網站內執行,或以您的網站名稱取代提供給 OpenWebConfiguration 方法的字串。

範例

Dim rootWebConfig As System.Configuration.Configuration
    rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot")
Dim connString As System.Configuration.ConnectionStringSettings
If (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count) Then
    connString = rootWebConfig.ConnectionStrings.ConnectionStrings("NorthwindConnectionString")
    If Not (Nothing = connString.ConnectionString) Then
        Console.WriteLine("Northwind connection string = {0}", connString.ConnectionString)
    Else
        Console.WriteLine("No Northwind connection string")
    End If
End If
         System.Configuration.Configuration rootWebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
            System.Configuration.ConnectionStringSettings connString;
            if (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count)
            {
                connString =
                    rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
                if (null != connString)
                    Console.WriteLine("Northwind connection string = \"{0}\"",
                        connString.ConnectionString);
                else
                    Console.WriteLine("No Northwind connection string");
            }

編譯程式碼

這項範例需要:

  • 根目錄 Web.config 檔中的 connectionStrings 項目,其中包含名為 NorthwindConnectionString 的連接。項目看起來可能如下所示:

    <connectionStrings>
      <add 
        name="NorthwindConnectionString" 
        connectionString="Data Source=serverName;Initial 
        Catalog=Northwind;Persist Security Info=True;User 
        ID=userName;Password=password"
        providerName="System.Data.SqlClient"
      />
    </connectionStrings>
    

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

    安全性注意事項:

    在組態檔中儲存使用者名稱和密碼等敏感性資訊時,應該使用受保護的組態將敏感的值加密。如需詳細資訊,請參閱 HOW TO:使用資料來源控制項時保護連接字串

穩固程式設計

如果 Web.config 檔中沒有指定的連接字串,就不會傳回任何物件。當讀取連接字串時,請確認檢查程式碼是否有傳回物件。

安全性

應使用 Windows 安全性設定來限制可以讀取組態檔的對象,以保護伺服器上的組態檔。您可以基於保護目的加密 connectionString 項目。如需詳細資訊,請參閱使用受保護的組態加密組態資訊

請參閱

參考

connectionStrings 項目 (ASP.NET 設定結構描述)

ConfigurationSettings