如何使用 C# 以编程方式下载 GitHub 数据

How to programmatically download GitHub data using C#

纽约时报在 https://github.com/nytimes/covid-19-data 维护着一个 GitHub 存储库。此存储库包含许可证、自述文件和两个数据文件。数据文件是us-states.csv和us-counties.csv。两者都包含按州或县划分的每日 COVID-19 病例数和死亡数的时间序列集合。

我正在尝试下载 us-states.csv 文件。我开发的程序是:

using System;
using System.Net;

namespace NYTimes_Console
    {

    // ************************************************* class Program

    class Program
        {

        // ****************************************************** Main

        static void Main ( string [ ] args )
            {
            byte [ ] bytes; 
            string   url = 
                        "https://raw.githubusercontent.com/nytimes/" + 
                        "covid-19-data/blob/master/us-states.csv";
            //string   url = 
            //            "https://github.com/nytimes/" + 
            //            "covid-19-data/blob/master/us-states.csv";


            try
                {
                using ( WebClient client = new WebClient ( ) )
                    {
                    client.Headers.Add("user-agent", "Anything");
                    bytes = client.DownloadData ( url );
                    }
                Console.WriteLine ( "Download Successful" );
                }
            catch ( Exception ex )
                {
                Console.WriteLine ( "Download Failed\n{0}",
                                    ex.Message.ToString ( ) );
                }
            Console.Write ( "Enter to exit");
            Console.ReadLine ( );
            }

        } // class Program

    } // namespace NYTimes_Console

当 url 为“https://github.com/nytimes/covid-19-data/blob/master/us-states.csv”时,我收到以下信息:

Download Failed
The underlying connection was closed: An unexpected error occurred on a send.

当我查看异常时,我发现:

InnerException = {"Received an unexpected EOF or 0 bytes from the transport stream."}

当 url 为“https://raw.githubusercontent.com/nytimes/covid-19-data/blob/master/us-states.csv”时,我收到以下信息:

Download Failed
The remote server returned an error: (404) Not Found.

并且 InnerException 为空。

我似乎误解了 GitHub 存储库和对它们的访问权限。

你可以尝试这样解决:

string url = "https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv";