netstandard 2.0 没有 AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

netstandard 2.0 does not have AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

我刚刚使用 net461/netstandard2.0net451 经典 dotnet 项目升级为多目标项目,并取得了一定的成功。

但是,在通过以下方式获取对遗留配置文件的访问时,是否遇到了 net461 的编译器错误:

AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

这在 netstandard2.0 中似乎不是问题 :) 有人知道任何解决方法或好的解决方案吗?

根据我在寻找 PlatformServices.Default.Application.ApplicationBasePath 的替代品时发现的 this article,它应该是以下之一:

  • AppDomain.CurrentDomain.SetupInformation.ApplicationName
  • Assembly.GetEntryAssembly().GetName().Name

就像你一样,我刚刚发现第一个在最近的 2.0 中不存在,所以我将使用 GetEntryAssembly 名称..

..但是请记住,GetEntryAssembly 在使用时可能是 null,即从像 xUnit 这样的测试运行器中使用,或者如果您的应用程序代码是 运行 来自另一个不属于您的 hosting/startup 模块等 - 因此 不是完美的替代品

将 ConfigurationManager 添加为 NuGet

<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
  <PackageReference Include="System.Configuration.ConfigurationManager" Version="4.5.0" />
</ItemGroup>

在 C# 中使用 ConfigurationManager

var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Log4NetLogger.Configure(configFile.FilePath);