【问题标题】:How to get the machine configuration filename in .NET Core如何在 .NET Core 中获取机器配置文件名
【发布时间】:2018-06-25 13:00:57
【问题描述】:

我正在将应用程序从 .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();
    }

这似乎与 .NET Core 兼容,除了以下声明

AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

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

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

任何帮助表示赞赏

斯蒂芬

【问题讨论】:

  • 假设您也在迁移到 .NET Core 的 JSON 配置文件方法,以及关联的 ConfigurationBuilderIConfiguration,最好将 IConfiguration 注入到您需要的位置。
  • 不,我们目前的目标是保持标准框架配置,我们正在尝试做一个非常小的代码更改,以使初始重构尽可能小。
  • ASP.NET Core 根本不支持旧式 ASP.NET 配置。如果您以 .NET Framework 为目标,您可能可以访问该 API 中的某些 API,但它不起作用。
  • ASP.NET Core 需要来自 Microsoft.Extensions.Configuration 的配置。如果要使用 .NET Framework 的 app.config,则必须使用 System.Configuration.ConfigurationManager 加载该配置并将其转换为适合 ASP.NET Core 使用的格式。没有内置支持,这是设计使然。

标签: c# .net asp.net-core .net-core


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多