如何在 .NET Core 中获取机器配置文件名

Rep*_*der 5 .net c# .net-core asp.net-core

我正在将应用程序从 .NET Framework 移植到 .NET Core(标准)。

在应用程序中,我们有以下代码

   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();
    }
Run Code Online (Sandbox Code Playgroud)

除了以下语句外,这似乎与 .NET Core 兼容

AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
Run Code Online (Sandbox Code Playgroud)

没有 SetupInformationAppDomain 上了。很公平,我读到它会导致问题等。但是,我还能如何在实用程序类中获取应用程序配置文件名?

请注意,此类将在控制台和 asp.net(核心)应用程序中使用。

任何帮助表示赞赏

斯蒂芬

oza*_*mut 6

如果您将库移植到 .Net Standard,也会出现同样的问题。解决方案是这样的;安装这个nuget包system.configuration.configurationmanager然后你可以使用:

 var conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
 var configFilePath = conf.FilePath;
Run Code Online (Sandbox Code Playgroud)

  • 这对于 exe 应用程序(和 .net core 应用程序)非常有效。我还需要获取使用 .netstandard2.0 库的 .net472 Web 应用程序的 web.config 路径。我怎样才能做到这一点? (2认同)