【问题标题】:Loading custom configuration files加载自定义配置文件
【发布时间】:2010-10-05 01:39:54
【问题描述】:

我知道我可以使用静态 ConfigurationManager.OpenExe(exePath) 方法打开与程序集相关的配置文件,但我只想打开与程序集无关的配置。只是一个标准的 .NET 配置文件。

【问题讨论】:

    标签: c# configuration


    【解决方案1】:

    Ricky 发的文章很好,可惜没有回答你的问题。

    要解决您的问题,您应该尝试以下代码:

    ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
    configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
    

    如果需要访问配置中的值,可以使用索引运算符:

    config.AppSettings.Settings["test"].Value;
    

    【讨论】:

    • @Oliver whateverYouLikeExtension,你的意思是你必须config.之后有something吗?
    • @Oliver 现在开始尝试,没有 :) 似乎可以正常工作
    • 我这样做了,但是当我访问 ConfigurationManager.ConnectionStrings 时,我仍然得到旧数据。我错过了什么?
    • @MAW74656:您不必访问ConfigurationManager.ConnectionStrings。相反,您必须从上面最后一条语句返回的 config 对象中读取值。
    • 对于其他搜索如何在完成后获取 appSettings 的人:var foo = config.AppSettings.Settings["test"].Value;
    【解决方案2】:

    配置文件只是一个 XML 文件,您可以通过以下方式打开它:

    private static XmlDocument loadConfigDocument()
    {
        XmlDocument doc = null;
        try
        {
            doc = new XmlDocument();
            doc.Load(getConfigFilePath());
            return doc;
        }
        catch (System.IO.FileNotFoundException e)
        {
            throw new Exception("No configuration file found.", e);
        }
        catch (Exception ex)
        {
            return null;
        }
    }
    

    然后通过以下方式检索值:

        // retrieve appSettings node
    
        XmlNode node =  doc.SelectSingleNode("//appSettings");
    

    【讨论】:

    • throw new Exception("No configuration file found.", e);之后检测到无法访问的代码。
    • 我将删除返回null,它不会真正达到。
    • 当您拥有来自 .Net 库的如此出色的类时,为什么要使用 XML。我不建议使用这个,设计不佳。接下来是什么?实现一个不同的字符串类...考虑一下。
    • @OtávioDécio 我可以添加 system.diagnostics 以在自定义 .config 文件中启用跟踪吗?
    • @FaizanRabbani 不确定自定义跟踪,但根据msdn.microsoft.com/en-us/library/ms733025(v=vs.110).aspx,您应该能够在配置文件中添加诊断。
    【解决方案3】:

    【讨论】:

      猜你喜欢
      • 2014-05-03
      • 1970-01-01
      • 2017-09-26
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多