Loading custom configuration files

2019-01-01 08:25发布

问题:

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.

回答1:

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);


回答2:

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\");


回答3:

I would use ConfigurationManager.OpenMappedExeConfiguration.