[C#] Github 透過 Octokit.net 操控 Github - 透過遞迴取得(下載)整個 Repository

2020-01-14

上一篇文章( Github 透過 Octokit.net 操控 Github - 檔案是否存在,刪除檔案,傳檔案上去)我們聊到了 如何檢查檔案是否存在,刪除,並且上傳新的檔案,這一篇我們聊一下如何把整個 Repository 下載下來。




這一篇主要是透過遞迴,來完成,在本地的地方,如果需要檔案夾就建立,如果是檔案就是開始下載下來,當然您都可以利用 git 工具下載,這邊透過 Octokit.net 當然是多此一舉,但是如果你要搞事情,當然就要會這些了。接下來就是分享 code 其實不難就直接看 code 吧 :)


//sample 網址 : https://github.com/donma/codenote //githubName: donma //repoName: codenote GetRepoFiles("donma", "codenote", "/");
private async static void GetRepoFiles(string githubName, string repoName, string dir) { //這 DONMATEST 可以任意都可以 var client = new GitHubClient(new ProductHeaderValue("DONMATEST")); //從網站上取得的 personal access token https://github.com/settings/tokens var tokenAuth = new Credentials(PersonalToken); client.Credentials = tokenAuth; var existingFiles = client.Repository.Content.GetAllContentsByRef(githubName, repoName, dir, "master").Result; //建立檔案夾 Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + repoName); if (dir != "/") { Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + repoName + Path.DirectorySeparatorChar + dir); } foreach (var f in existingFiles) { //檔案的處理 if (f.Type.StringValue == "file") { Console.ForegroundColor = ConsoleColor.Green; Console.Write("" + f.Name + "(" + (f.Size / (decimal)1024).ToString("#.##") + " KB) =>"); Console.ForegroundColor = ConsoleColor.DarkCyan; if (dir == "/") { Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory + repoName + Path.DirectorySeparatorChar + f.Name); WebClient wc = new WebClient(); wc.DownloadFile(f.DownloadUrl, AppDomain.CurrentDomain.BaseDirectory + repoName + Path.DirectorySeparatorChar + f.Name); } else { Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory + repoName + Path.DirectorySeparatorChar + dir + Path.DirectorySeparatorChar + f.Name); WebClient wc = new WebClient(); wc.DownloadFile(f.DownloadUrl, AppDomain.CurrentDomain.BaseDirectory + repoName + Path.DirectorySeparatorChar + dir + Path.DirectorySeparatorChar + f.Name); } } //檔案夾的處理 else if (f.Type.StringValue == "dir") { if (dir == "/") { //遞迴處理 GetRepoFiles(githubName, repoName, f.Name); } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Create Path => " + dir + Path.DirectorySeparatorChar + f.Name); GetRepoFiles(githubName, repoName, dir + Path.DirectorySeparatorChar + f.Name); } } } Console.ForegroundColor = ConsoleColor.White; }
筆記一下,也給之後有需要的朋友直接複製貼上,如果覺得我寫的不好,就自己在改寫吧。


當麻許的碎念筆記 2014 | Donma Hsu Design.