C# 加载自定义配置文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/505566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loading custom configuration files
提问by Adam
I know I can open config files that are related to an assembly with the static ConfigurationManager.OpenExe(exePath)
method but I just want to open a config that is not related to an assembly. Just a standard .NET config file.
我知道我可以使用静态ConfigurationManager.OpenExe(exePath)
方法打开与程序集相关的配置文件,但我只想打开与程序集无关的配置。只是一个标准的 .NET 配置文件。
采纳答案by Oliver
the articles posted by Ricky are very good, but unfortunately they don't answer your question.
Ricky 发表的文章非常好,但不幸的是它们没有回答您的问题。
To solve your problem you should try this piece of code:
要解决您的问题,您应该尝试这段代码:
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
If need to access a value within the config you can use the index operator:
如果需要访问配置中的值,您可以使用索引运算符:
config.AppSettings.Settings["test"].Value;
回答by Otávio Décio
The config file is just an XML file, you can open it by:
配置文件只是一个 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;
}
}
and later retrieving values by:
然后通过以下方式检索值:
// retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings");