File Download in C# .NET Core

Pratham Jain 221 Reputation points
2022-10-04T04:59:51.85+00:00

Hi All,

I am developing an application in C# .NET Core and angular. I need to implement a file download functionality in the application where user will download the file from URL in his Downloads folder. I came to know that C# WebClient class has become obsolete and can not be used to achieve the same.

Please advise how can I achieve the same ASAP.

Thanks & Regards,
Pratham Jain

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,380 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 36,471 Reputation points Microsoft Vendor
    2022-10-04T06:50:15.97+00:00

    Hi @Pratham Jain ,

    Welcome to Q&A.

    We don't recommend that you use the WebClient class for new development. Instead, use the System.Net.Http.HttpClient class.

    This is the demo code:

    // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.  
    static readonly HttpClient client = new HttpClient();  
      
    static async Task Main()  
    {  
        // Call asynchronous network methods in a try/catch block to handle exceptions.  
        try	  
        {  
            HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");  
            response.EnsureSuccessStatusCode();  
            string responseBody = await response.Content.ReadAsStringAsync();  
            // Above three lines can be replaced with new helper method below  
            // string responseBody = await client.GetStringAsync(uri);  
      
            Console.WriteLine(responseBody);  
        }  
        catch(HttpRequestException e)  
        {  
            Console.WriteLine("\nException Caught!");	  
            Console.WriteLine("Message :{0} ",e.Message);  
        }  
    }  
    

    Best Regards,
    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful