如何在 C# .NET 中从 GitHub 下载原始文件

问题描述

我正在尝试使用 DownloadFile 类的 System.Net.WebClient 方法从 GitHub 下载文件。我尝试从 here 下载 .txt 文件,结果是 this。这显然是页面的 HTML 代码,而不是文件。尝试谷歌搜索一些解决方案,但没有一个奏效。代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;

namespace download_file_test
{
    class Program
    {
        static void Main(string[] args)
        {
            using (WebClient wc = new WebClient())
            {
                wc.Headers.Add("a","a");
                try
                {
                    wc.DownloadFile("https://github.com/github/platform-samples/blob/master/LICENSE.txt",@"C:/Users/User/Desktop/test/test.txt");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                Console.ReadKey();
                Console.ReadLine();
            }
        }
    }
}

解决方法

您的代码下载 GitHub 页面的 HTML,而不是它显示的文件。

尝试下载 raw version instead,方法是将 raw. 作为其子域的前缀并从中删除 blob 部分:

wc.DownloadFile("https://raw.githubusercontent.com/github/platform-samples/master/LICENSE.txt",@"C:/Users/User/Desktop/test/test.txt");