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

标签 c# .net asp.net-core .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();
    }

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

AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

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

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

感谢任何帮助

斯蒂芬

最佳答案

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

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

关于c# - 如何在 .NET Core 中获取机器配置文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51024110/

相关文章:

c# - DotNetOpenAuth 的教程在哪里以及如何解决其示例中的编译错误

c# - 函数中的 InvalidAsynchronousStateException 用于检查控制是否需要调用

C# - 如何在列表中添加所有 system.drawing.color 项目?

c# - 系统.Data.SqlClient.SqlException : Login failed for user

.net - 使用 oracle.dataaccess.dll 时出错

c# - Linq Any() 抛出错误 : String was not recognized as a valid boolean

c# - 由于格式化,XML 反序列化在十进制解析时崩溃

.net - Web.config 转换可以与 App.config 文件一起使用吗?

asp.net - 如何更改默认文化?

asp.net-core - Core 3.1 Blazor 应用程序中的 onclick 不起作用