加载自定义配置文件

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

117854 次浏览

这个配置文件只是一个 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");

里奇发表的文章很好,但不幸的是他们没有回答你的问题。

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

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

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

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