读取 asp.net 中的自定义配置文件

本文关键字:自定义 配置文件 asp net 读取 | 更新日期: 2023-09-27 18:37:18

如何使用 asp.net 的 C# 代码中的 WebConfigurationManager 从自定义配置文件(例如 abc.config)读取连接字符串?

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

这似乎行不通。

读取 asp.net 中的自定义配置文件

你可以使用这个技巧:这是我的自定义方法 - 从 Web 根目录使用 webapp.config。读取所有应用程序设置并返回;

//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>

我认为你不能用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;

        }