我目前正在处理两个项目:.NET Standard 2.0 类库和 .NET Framework 4.6.2 控制台应用程序。在我的 .NET Standard 库中,我使用 System.Diagnostics.EventLog 库。
我在.NET Standard项目中写了一个方法:
public static void LogTest()
{
if (!EventLog.SourceExists(System.AppDomain.CurrentDomain.FriendlyName))
EventLog.CreateEventSource(System.AppDomain.CurrentDomain.FriendlyName, "Application");
}
但是,当我尝试从 .NET Framework 控制台应用程序调用 LogTest 方法时,遇到错误,指出
System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Diagnostics.EventLog, Version=8.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.'
我的印象是 .NET Framework 项目应该自动从 .NET Standard 库复制这些依赖项,但事实并非如此。所以我添加了
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
System.PlatformNotSupportedException: 'EventLog access is not supported on this platform.'
例外。当我调查时,我发现 System.Diagnostics.EventLog.dll 适用于构建目录中的 .Net Standard 2.0。我从 Nuget 目录 (C:\Users\XXX.nuget\packages\system.diagnostics.eventlog\8.0.0) 复制了 .NET Framework 4.6.2 的 System.Diagnostics.EventLog.dll。
我找不到这个问题的文档,并询问了Github Copilot,它说将nuget包也添加到NET Framework项目中,看起来它解决了问题,但是这不是一个好的解决方案,因为我必须了解其他项目中的每个 nuget 包引用。
我在这里上传了一个示例项目:https://github.com/sahin52/NetStandardInNetFrameworkProjExcample你可以构建并看到同样的问题,并且ClassLibrary1\ClassLibrary1.csproj有一行CopyLocalLockFileAssemblies,目前已被注释掉,你可以通过删除评论标签来测试它。
我怎样才能很好地解决这个问题呢?预先感谢。
编辑:这不仅与这个包相关,我对ModifyRegistry也遇到了同样的错误:
System.PlatformNotSupportedException: Registry is not supported on this platform.
。
尝试此操作,您可以使用 .NET 平台扩展。这允许您在 .NET Core 项目中使用特定于 Windows 的库,而无需通过 .NET Standard。
首先您需要 Windows 兼容包。
dotnet add package Microsoft.Windows.Compatibility --version 8.0.0
然后就可以安装EventLog库了。
dotnet add package System.Diagnostics.EventLog --version 8.0.0