How to get file's contents on Git using LibGit2Sharp?

I checked code in BlobFixture.cs and found some tests about reading file’s contents like below.

using (var repo = new Repository(BareTestRepoPath))
{
    var blob = repo.Lookup<Blob>("a8233120f6ad708f843d861ce2b7228ec4e3dec6");

    var contentStream = blob.GetContentStream();
    Assert.Equal(blob.Size, contentStream.Length);

    using (var tr = new StreamReader(contentStream, Encoding.UTF8))
    {
        string content = tr.ReadToEnd();
        Assert.Equal("hey there\n", content);
    }
}

But I cannot find a test that getting file’s contents based on file’s name. Is it possible to do that, if so how?

  • Reverting to a previous commit in Git for visual studio 2012
  • .NET projects build automation with NAnt/MSBuild + SVN
  • What is the optimal way to organize shared .net assemblies in SVN?
  • How to get the current/active branch with LibGit2Sharp?
  • Prevent connection string from being committed to repository
  • SVN Revision Version in .NET Assembly w/ out CC.NET
  • Gradle: how to clone a git repo in a task?
  • Removed sensitive file from GitHub history, but I can still access it
  • GIT push not pushing commits to remote
  • git status shows a file that I have listed explicitly in my .gitignore file
  • Git nested repos
  • Git: need to recursively 'git rm' the contents of all bin and obj folders
  • One Solution collect form web for “How to get file's contents on Git using LibGit2Sharp?”

    Each Tree holds a collection of TreeEntry. A TreeEntry holds some metadata (name, mode, oid, …) about a pointed at GitObject. The GitObject can be accessed through the Target property of a TreeEntry instance.

    Most of the time, a TreeEntry will point to a Blob or another Tree.

    The Tree type exposes an indexer which accepts a path to easily retrieve the finally pointed at TreeEntry. As a convenience method, the Commit exposes such an indexer as well.

    Thus your code could be expressed this way.

    using (var repo = new Repository(BareTestRepoPath))
    {
        var commit = repo.Lookup<Commit>("deadbeefcafe"); // or any other way to retreive a specific commit
        var treeEntry = commit["path/to/my/file.txt");
    
        Debug.Assert(treeEntry.TargetType == TreeEntryTargetType.Blob);
        var blob = (Blob)treeEntry.Target;
    
        var contentStream = blob.GetContentStream();
        Assert.Equal(blob.Size, contentStream.Length);
    
        using (var tr = new StreamReader(contentStream, Encoding.UTF8))
        {
            string content = tr.ReadToEnd();
            Assert.Equal("hey there\n", content);
        }
    }
    
    Git Baby is a git and github fan, let's start git clone.