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.
3 Answers
the articles posted by Ricky are very good, but unfortunately they don't answer your question.
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;
13 Comments
Svish
@Oliver By
whateverYouLikeExtension, do you mean that you must have something after config.?Svish
@Oliver Got around to try now, and seems to work fine without :)
MAW74656
I did this, but when I access ConfigurationManager.ConnectionStrings I'm still gettting the old data. What am I missing?
Oliver
@MAW74656: You don't have to access
ConfigurationManager.ConnectionStrings. Instead you have to read the value from the config object returned from the last statement above.Roro
For anyone else searching on how to get the appSettings after this is done: var foo = config.AppSettings.Settings["test"].Value;
|
The config file is just an XML file, you can open it by:
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");
6 Comments
Oybek
Unreachable code detected after
throw new Exception("No configuration file found.", e);.Otávio Décio
I'll remove the return null, it won't really be reached.
Yuki
why to use XML when you have such great classes from .Net library. I wouldn't suggest using this, poor on design. What next? implement a different string class... consider this.
FaizanHussainRabbani
@OtávioDécio Can I add system.diagnostics to enable tracing in custom .config file?
Otávio Décio
@FaizanRabbani not sure about the custom tracing, but according to msdn.microsoft.com/en-us/library/ms733025(v=vs.110).aspx you should be able to add diagnostics on the config file.
|