【问题标题】:read custom config file in asp.net在 asp.net 中读取自定义配置文件
【发布时间】:2012-06-18 23:16:46
【问题描述】:

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

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

这似乎不起作用。

【问题讨论】:

  • 你是什么意思似乎不起作用?你有例外吗?它没有加载吗?什么是行为?
  • 正确检查您的config path。应该很简单。 conf 对象是否为空?
  • 它不是从 abc.config 读取一些 SQLEXPRESS 作为数据源(不同的连接字符串)
  • SQLEXPRESS 是第 0 个元素,来自 abc.config 的连接字符串是第 1 个元素。
  • 这是什么意思?这些信息似乎与问题无关。你能分享一下文件吗?你告诉它一个自定义配置,不是一个标准的web.config文件。

标签: c# asp.net configuration config webconfigurationmanager


【解决方案1】:

你可以使用这个技巧: 它是我的自定义方法 - 使用 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>

【讨论】:

  • 如果我没有 appSettings 节点怎么办?
  • 所有 XML 都需要 root 和 item 元素,它是一个标准的 XML,您需要 root(配置)和 Item 元素(appSettings)以及您想要的属性(例如'WebApp-FixedTopMenu')。跨度>
【解决方案2】:

我认为您无法使用 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;


        }

【讨论】:

    猜你喜欢
    • 2016-03-27
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多