2012-06-15 42 views
1

如何從asp.net的C#代碼中使用WebConfigurationManager從自定義配置文件(比如說abc.config)讀取連接字符串?閱讀asp.net中的自定義配置文件

Configuration conf = WebConfigurationManager.OpenWebConfiguration("~/abc.config"); 

這似乎不起作用。

+0

什麼,你似乎就意味着沒有工作?你有例外嗎?它沒有加載?什麼是行爲主義? –

+0

正確檢查你的「配置路徑」。它應該很簡單。 'conf'對象是否爲空? –

+0

它讀取一些SQLEXPRESS作爲數據源(不同的連接字符串),而不是從abc.config – Sam

回答

1

我不認爲你可以通過webconfigurationmanager閱讀它。你會讀到這樣任何XML文件,因爲它是一個XML文件

public static string GetSingleValue(string strXPathExpression, string strAttributeName) 
     { 
      XmlNode node = GetNode(strXPathExpression); 
      if (node != null) 
      { 
       XmlAttribute attribute = node.Attributes[strAttributeName]; 
       if (attribute != null) 
        return attribute.Value; 
      } 

      return string.Empty; 


     } 
+0

這是否準確? – Sam

+0

是的,根據我的知識 – Rab

3

您可以使用這一招:用webapp.config 的我自定義的方法 - 從Web根目錄。讀取所有應用程序設置並返回;

//Read WebAppConfiguration 
public static AppSettingsSection ReadAllWebappConfig() 
{ 
    string physicalWebAppPath = ""; 
    AppSettingsSection appSettings; 

    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); 
    physicalWebAppPath = System.Web.Hosting.HostingEnvironment.MapPath("~/webapp.config"); 

    if (System.IO.File.Exists(physicalWebAppPath)) 
    { 
     fileMap.ExeConfigFilename = physicalWebAppPath; 
     Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); 
     appSettings = (AppSettingsSection)config.GetSection("appSettings"); 
    } 
    else 
     appSettings = null; 

    return appSettings; 
} 

webapp.config樣本:

<configuration> 
    <appSettings> 
    <add key="WebApp-FixedTopMenu" value="true"/> 
    <add key="WebApp-FixedTopMenuThickness" value="true"/> 
    </appSettings> 
</configuration> 
+0

如果我沒有appSettings節點會怎麼樣? – Shesha

+0

所有的XML都需要root和item元素,它是一個標準的XML,您需要根(配置)和Item元素(appSettings)以及您期望的屬性(如'WebApp-FixedTopMenu')。 – mRizvandi