Search code examples
c#webclient

How to download a raw file from GitHub in C# .NET


I am trying to use the DownloadFile method of the System.Net.WebClient class to download files from GitHub. I tried downloading a .txt file from here, and the result was this. That's clearly the HTML code of the page, not the file. Tried googling some solutions, none of them worked. Here's the code:

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();
            }
        }
    }
}

Solution

  • Your code downloads the HTML of the GitHub page, not the file that it displays.

    Try to download the raw version instead by using raw.githubusercontent.com as domain and removing the blob part from it:

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