Posted in:

I recently needed to write some code in C# that could list the contents of a GitHub repository, and download the contents of specific files.

There is actually a GitHub API, which means that this simple URL (https://api.github.com/repos/markheath/azure-deploy-manage-containers/contents) can be used to list all the files in one of my GitHub repos.

Calling this from C# is relatively straightforward, with the exception that you must provide a user agent header or you'll get a 403 response.

Here's some simple sample code that gets the contents of a GitRepo and displays the URL to download each file (and using Newtonsoft.Json to help with the JSON parsing). Notice that for directories, you have to call another URL to get the files in that directory.

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.UserAgent.Add(
    new ProductInfoHeaderValue("MyApplication", "1"));
var repo = "markheath/azure-deploy-manage-containers";
var contentsUrl = $"https://api.github.com/repos/{repo}/contents";
var contentsJson = await httpClient.GetStringAsync(contentsUrl);
var contents = (JArray)JsonConvert.DeserializeObject(contentsJson);
foreach(var file in contents)
{
    var fileType = (string)file["type"];
    if (fileType == "dir")
    {
        var directoryContentsUrl = (string)file["url"];
        // use this URL to list the contents of the folder
        Console.WriteLine($"DIR: {directoryContentsUrl}");
    }
    else if (fileType == "file")
    {
        var downloadUrl = (string)file["download_url"];
        // use this URL to download the contents of the file
        Console.WriteLine($"DOWNLOAD: {downloadUrl}");
    }
}

If you need to fetch the contents of a specific branch, you can simply append ?ref=branchname as a query string parameter.

Comments

Comment by quintonn

this is interesting.
Been looking for an easy github api to get the contents.
Is there no way to get all the files at once, maybe in a zip or something?

quintonn
Comment by Mark Heath

I don't know - wasn't something I needed to do, but wouldn't surprise me if its possible as you can download a zip from the github website

Mark Heath