如何使用LibGit2Sharp从Git存储库中获取文件二进制数据?

Nic*_*ick 6 c# git gitsharp libgit2sharp

我决定尝试将我的项目从使用GitSharp迁移到LibGit2Sharp,因为不再主动维护GitSharp.使用GitSharp,我能够在给定分支的情况下访问检查到我的仓库中的任何文件的原始字节.我无法使用LibGit2Sharp找到任何文档或示例代码.

有人能给我以及如何做到这一点的例子吗?

nul*_*ken 3

Blob类型公开Content一个返回byte[].

以下测试从BlobFixture.cs文件中提取并演示了此属性的用法。

[Test]
public void CanReadBlobContent()
{
    using (var repo = new Repository(BareTestRepoPath))
    {
        var blob = repo.Lookup<Blob>("a8233120f6ad708f843d861ce2b7228ec4e3dec6");
        byte[] bytes = blob.Content;
        bytes.Length.ShouldEqual(10);

        string content = Encoding.UTF8.GetString(bytes);
        content.ShouldEqual("hey there\n");
    }
}
Run Code Online (Sandbox Code Playgroud)

在此特定测试中,通过该方法直接检索 Blob GitObject LookUp()Files您还可以从的属性访问 Blob Tree

关于您更具体的请求,以下单元测试应该向您展示如何从Branch.

[Test]
public void CanRetrieveABlobContentFromTheTipOfABranch()
{
    using (var repo = new Repository(BareTestRepoPath))
    {
        Branch branch = repo.Branches["br2"];
        Commit tip = branch.Tip;
        Blob blob = (Blob)tip["README"].Target;
        byte[] content = blob.Content;

        content.Length.ShouldEqual(10);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:此测试显示了访问 a Blob(作为抽象TreeEntry)的另一种方式。于是,使用了cast。