加载自定义配置文件

Ada*_*dam 115 c# configuration

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

Oli*_*ver 235

Ricky发布的文章非常好,但不幸的是他们没有回答你的问题.

要解决您的问题,您应该尝试这段代码:

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

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

config.AppSettings.Settings["test"].Value;
Run Code Online (Sandbox Code Playgroud)

  • @Oliver现在尝试一下,似乎没有:) (4认同)
  • 对于其他任何人在完成此操作后搜索如何获取appSettings:var foo = config.AppSettings.Settings ["test"].Value; (3认同)
  • @Svish:我不记得了。你有没有尝试过? (2认同)

Otá*_*cio 9

配置文件只是一个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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

    // retrieve appSettings node

    XmlNode node =  doc.SelectSingleNode("//appSettings");
Run Code Online (Sandbox Code Playgroud)

  • 为什么要在.Net库中拥有如此优秀的类时使用XML.我不建议使用这个,设计很差.接下来是什么?实现一个不同的字符串类......考虑一下. (7认同)