133

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 3

268

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;
Sign up to request clarification or add additional context in comments.

13 Comments

@Oliver By whateverYouLikeExtension, do you mean that you must have something after config.?
@Oliver Got around to try now, and seems to work fine without :)
I did this, but when I access ConfigurationManager.ConnectionStrings I'm still gettting the old data. What am I missing?
@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.
For anyone else searching on how to get the appSettings after this is done: var foo = config.AppSettings.Settings["test"].Value;
|
8

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

Unreachable code detected after throw new Exception("No configuration file found.", e);.
I'll remove the return null, it won't really be reached.
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.
@OtávioDécio Can I add system.diagnostics to enable tracing in custom .config file?
@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.
|
4

I would use ConfigurationManager.OpenMappedExeConfiguration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.