5

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();
            }
        }
    }
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
Zamdie
  • 53
  • 1
  • 5

1 Answers1

6

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");
Martin Braun
  • 10,906
  • 9
  • 64
  • 105
  • It worked! However, how could I download a `.zip` file using this method? – Zamdie Jan 20 '21 at 22:37
  • Prefixing `raw.` and removing `blob` prompts me to download the file – Zamdie Jan 20 '21 at 22:40
  • @Zamdie [This](https://stackoverflow.com/questions/4769032/how-do-i-download-zip-file-in-c) should help you to get on track. But honestly, it might be better off to simply clone the repository. Having `git` as dependency might be alright for your program. If you are using .NET Core, you can look at [LibGit2Sharp](https://edi.wang/post/2019/3/26/operate-git-with-net-core). Otherwise, please take a look at [this question](https://stackoverflow.com/questions/5432245/is-there-some-way-to-work-with-git-using-net-application). – Martin Braun Jan 20 '21 at 22:42
  • @Zamdie It might prompts you in the browser, because your browser doesn't handle the content type properly. It should work in your code nonetheless. – Martin Braun Jan 20 '21 at 22:43