RepellantCoder
RepellantCoder

Reputation: 181

How to get the machine configuration filename in .NET Core

I am porting an application from .NET Framework to .NET Core (Standard).

Within the application, we have the following code

   public LogMessageListenerFromConfig()
        : this(AppDomain.CurrentDomain.BaseDirectory.ConfigurationFile, LoggingSection.DefaultName)
    { }

    public LogMessageListenerFromConfig(string section)
        : this(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, section)
    { }

    public LogMessageListenerFromConfig(string filename, string section)
    {
        // todo: set up a file watcher and refresh the listeners (etc.) when it changes.
        var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filename };
        var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

        _section = LoggingSection.Section(configuration, section);
        Refresh();
    }

This appears to be compatible with .NET Core apart from the following statement

AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

There is no SetupInformation on an AppDomain anymore. Fair enough I read that it would cause issues etc. However, how else can I get the application configuration file name in a utility class?

Please be aware that this class will be used in both console and asp.net (core) applications.

Any help appreciated

Stephen

Upvotes: 13

Views: 4555

Answers (1)

ozanmut
ozanmut

Reputation: 3234

Same problem if you are porting a library to .Net Standard. Solution is this; install this nuget package system.configuration.configurationmanager then you can use:

 var conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
 var configFilePath = conf.FilePath;

Upvotes: 8

Related Questions