Search code examples
c#httpclientwebclient

How do I specify the destination to download the file using httpclient


I have the need to convert this PS cmdlet to C#

invoke-webrequest -uri [uri] -method GET -headers [myHeader] -outfile  [myFile]

where [uri] is the download link, [myHeader] contains my apikey and my outfile is the name of the destination file.

The invoke-webrequest in PS works but my project requires C# code. I can use the following code for the normal get or post action if I were dealing with the standard json:

        var msg = new HttpRequestMessage(HttpMethod.Get, [uri]);
        msg.Headers.Add(_apiKeyTag, _myKey);
        var resp = await _httpClient.SendAsync(msg);

Assuming _httpClient is created by new HttpClient and assuming the download link [uri] exists. The file to be downloaded is either a pdf, jpg, img or csv file. I am not sure how to convert the above comdlet in PS to C#.

How do I specify my destination file? (I am referring to the option -outfile in PS)


Solution

  • Never use anything but HttpClient. If you catch yourself typing WebClient of anything other than HttpClient, kindly slap your hand away from the keyboard.

    You want to download a file with HttpClient? Here is an example of how to do that:

    private static readonly HttpClient _httpClient = new HttpClient();
    
    private static async Task DoSomethingAsync()
    {
        using (var msg = new HttpRequestMessage(HttpMethod.Get, new Uri("https://www.example.com")))
        {
            msg.Headers.Add("x-my-header", "the value");
            using (var req = await _httpClient.SendAsync(msg))
            {
                req.EnsureSuccessStatusCode();
                using (var s = await req.Content.ReadAsStreamAsync())
                using (var f = File.OpenWrite(@"c:\users\andy\desktop\out.txt"))
                {
                    await s.CopyToAsync(f);
                }
            }
        }
    }
    

    You can do anything you want with HttpClient. No reason to use RestClient, WebClient, HttpWebRequest or any of those other "wannabe" Http client implementations.