Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 278
RepellantCoder Avatar asked Oct 16 '22 16:10

RepellantCoder


1 Answers

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;
like image 162
ozanmut Avatar answered Oct 20 '22 15:10

ozanmut