-->

阅读在asp.net自定义配置文件(read custom config file in asp.n

2019-09-18 04:26发布

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

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

这似乎并没有工作。

Answer 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;


        }


Answer 2:

您可以使用这一招:它的我自定义的方法 - 使用webapp.config从Web根目录。 的ReadL所有应用设置并返回;

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


文章来源: read custom config file in asp.net