'LibGit2Sharp.Core.NativeMethods' 的类型初始值设定项抛出异常

The type initializer for 'LibGit2Sharp.Core.NativeMethods' threw an exception

我正在开发 C# 控制台应用程序 (.NET 4.6.1),当 运行 运行它的可执行文件时,我收到以下错误:

The type initializer for 'LibGit2Sharp.Core.NativeMethods' threw an exception.

错误描述:

at LibGit2Sharp.Core.NativeMethods.git_repository_open(git_repository*& repository, FilePath path)
at LibGit2Sharp.Core.Proxy.git_repository_open(String path)
at LibGit2Sharp.Repository..ctor(String path, RepositoryOptions options, RepositoryRequiredParameter requiredParameter)
at LibGit2Sharp.Repository..ctor(String path)
at MyProj.MyClass.GetMaxBranchVersion(String repoPath)

内部异常:

System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime.InteropServices.RuntimeInformation, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. File name: 'System.Runtime.InteropServices.RuntimeInformation, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' at LibGit2Sharp.Core.Platform.get_OperatingSystem() at LibGit2Sharp.Core.NativeMethods..cctor()

现在,该项目的代码在调试时或仅使用 Visual Studio 运行 时工作正常 - 尝试将其 运行 作为可执行文件时出现错误。 问题不在于 GetMaxBranchVersion 方法本身,因为我尝试根本不调用它,这只会导致错误出现,当 运行 下一个方法时.

我尝试按照 this answer 将以下配置项添加到 .csproj 文件,但不幸的是,它没有解决我的问题:

<PropertyGroup>
..
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
..
</PropertyGroup>

可能的原因是什么?

我知道提供的信息可能不多,但如果需要,我可以提供更多详细信息。

我通过以下操作成功解决了我的问题:

  1. 将项目的 Target Framework 更改为 .NET 4.7
  2. 复制了 System.Runtime.InteropServices.RuntimeInformation.dll 文件夹中的 运行 可执行文件

此时我又得到一个错误:

System.DllNotFoundException: Unable to load DLL 'git2-6311e88': The specified module could not be found. (Exception from HRESULT: 0x8007007E) at LibGit2Sharp.Core.NativeMethods.git_libgit2_init()
at LibGit2Sharp.Core.NativeMethods.LoadNativeLibrary() at LibGit2Sharp.Core.NativeMethods..cctor()

感谢 this answer 我能够通过以下方式解决这个问题 还要复制 git2-6311e88.dll(我需要 x86 版本,它通常位于 bin/debugbin/release 文件夹中,在 lib/os-version,在我的例子中 lib/win32)

瞧瞧!有用!祝所有遇到同样问题的人好运。