read custom config file in asp.net

*爱你&永不变心* 提交于 2019-12-08 03:17:17

问题


How do I read connection strings from custom config file (say abc.config) using WebConfigurationManager from asp.net's C# code?

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

This doesn't seem to work.


回答1:


I dont think you can read it with webconfigurationmanager. you will have read like any xml file as it is an xml file

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;


        }



回答2:


you can use this trick: its my custom method- using webapp.config from web root. readl all app settings and return;

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

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


来源:https://stackoverflow.com/questions/11058235/read-custom-config-file-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!