如何从GitHub链接获取文件列表?
例如,从这个GitHub存储库链接 - https://github.com/crs2007/ActiveReport/tree/master/ActiveReport/SQLFiles
我们可以看到有SQL文本文件 - GitHub page with the relevant files(Pic)
我想获得这些文件的列表 -
先谢谢...
答案 0 :(得分:2)
您应该可以使用GitHub Contents API
提出以下请求:
curl https://api.github.com/repos/crs2007/ActiveReport/contents/ActiveReport
Github将返回包含目录内容的JSON。
您可以通过多种方式在C#中执行此操作,可能会建议使用Octokit这样的内容,因为他们解决了您可能遇到的大多数问题。如果您不能使用外部库,下面的示例显示了如何使用普通的HttpClient来实现相同的功能,尽管需要更多的管道:
class Program
{
static void Main()
{
Task.Factory.StartNew(async () =>
{
var repoOwner = "crs2007";
var repoName = "ActiveReport";
var path = "ActiveReport";
var httpClientResults = await ListContents(repoOwner, repoName, path);
PrintResults("From HttpClient", httpClientResults);
var octokitResults = await ListContentsOctokit(repoOwner, repoName, path);
PrintResults("From Octokit", octokitResults);
}).Wait();
Console.ReadKey();
}
static async Task<IEnumerable<string>> ListContents(string repoOwner, string repoName, string path)
{
using (var client = GetGithubHttpClient())
{
var resp = await client.GetAsync($"repos/{repoOwner}/{repoName}/contents/{path}");
var bodyString = await resp.Content.ReadAsStringAsync();
var bodyJson = JToken.Parse(bodyString);
return bodyJson.SelectTokens("$.[*].name").Select(token => token.Value<string>());
}
}
static async Task<IEnumerable<string>> ListContentsOctokit(string repoOwner, string repoName, string path)
{
var client = new GitHubClient(new ProductHeaderValue("Github-API-Test"));
// client.Credentials = ... // Set credentials here, otherwise harsh rate limits apply.
var contents = await client.Repository.Content.GetAllContents(repoOwner, repoName, path);
return contents.Select(content => content.Name);
}
private static HttpClient GetGithubHttpClient()
{
return new HttpClient
{
BaseAddress = new Uri("https://api.github.com"),
DefaultRequestHeaders =
{
// NOTE: You'll have to set up Authentication tokens in real use scenario
// NOTE: as without it you're subject to harsh rate limits.
{"User-Agent", "Github-API-Test"}
}
};
}
static void PrintResults(string source, IEnumerable<string> files)
{
Console.WriteLine(source);
foreach (var file in files)
{
Console.WriteLine($" -{file}");
}
}
}