Search code examples
c#gitvisual-studio-2017console-applicationlibgit2sharp

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


I am working on a C# console application (.NET 4.6.1) and when running its executable I get the following error:

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

Error description:

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)

Inner exception:

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()

Now, the project's code works fine when debugging it or just running it with Visual Studio - the error comes up when trying to run it as an executable. The issue is not really with the GetMaxBranchVersion method itself, because I tried not calling it at all and this only caused the error to come up anyway, when running the next method.

I tried adding the following configuration items to the .csproj file as per this answer but unfortunately, it did not solve my problem:

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

What could be the possible reason?

I understand the information provided might not be a lot, but I can provide additional details if needed.


Solution

  • I managed to solve my issue doing the following:

    1. Changed the Target Framework for the project to .NET 4.7
    2. Copied the System.Runtime.InteropServices.RuntimeInformation.dll inside the folder where I was trying to run the executable from

    At this point I got another error:

    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()

    Thanks to this answer I was able to overcome this issue by copying also the git2-6311e88.dll (the x86 version was needed in my case, which is normally located on your bin/debug or bin/release folder, under lib/os-version, in my case lib/win32)

    And voilà! It works! Good luck to anyone struggling with the same issue.