Download file in C# .Net Core

Pratham Jain 221 Reputation points
2022-10-03T14:07:55.503+00:00

Hi All,

I am developing an application in angular and .NET Core. I need to implement download file functionality where user will be able to download file from URL in downloads folder. I came to know that WebClient is obsolete and can not be used in .NET Core for downloading a file.

Please advise how can I achieve the same ASAP.

Thanks and Regards,
Pratham

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,106 Reputation points Microsoft Vendor
    2022-10-04T02:56:33.683+00:00

    Hi @Pratham Jain ,

    I need to implement download file functionality where user will be able to download file from URL in downloads folder.

    To download file from the file folder (in the wwwroot folder, if the file folder doesn't in the wwwroot folder, refer to this link), you can get the file path via the IWebHostEnvironment, then read the file content and return a File object to the client.

    [Route("api/[controller]")]  
    [ApiController]  
    public class ToDoController : ControllerBase  
    {  
        private readonly IWebHostEnvironment environment;  
        public ToDoController(IWebHostEnvironment hostEnvironment)  
        {   
            environment = hostEnvironment;  
        }  
        [HttpGet("download")]  
        public IActionResult Download()  
        {  
            var filepath = Path.Combine(environment.WebRootPath, "images", "Image1.png");  
            return File(System.IO.File.ReadAllBytes(filepath), "image/png", System.IO.Path.GetFileName(filepath));  
        }  
    

    Then, in the Index view page, we can add a hyperlink to call this API method and download file:

    <a href='~/api/Todo/download' download>Download File From Folder</a>  
    

    To download file from URL, you can use HttpClient or IHttpClientFactory, refer to the following code:

    Create a DownloadExtention.cs :

    public static class DownloadExtention  
    {   
        public static async Task<byte[]?> GetUrlContent(string url)  
        {  
            using (var client = new HttpClient())  
            using (var result = await client.GetAsync(url))  
                return result.IsSuccessStatusCode ? await result.Content.ReadAsByteArrayAsync() : null;  
        }  
    }  
    

    Then in the API method, create a method as below:

        [HttpGet("downloadfromurl")]  
        public IActionResult DownloadFromUrl(string url)  
        {  
            var result = DownloadExtention.GetUrlContent(url);  
            if (result != null)  
            {   
                return File(result.Result, "image/png", "test.jpg");  
            }  
            return Ok("file is not exist");  
        }  
    

    Then, add the download hyperlink:

    <a href='~/api/Todo/downloadfromurl?url=https://www.learningcontainer.com/wp-content/uploads/2020/07/Large-Sample-Image-download-for-Testing.jpg' download>Download File</a>  
    

    The output as below:

    247233-1.gif


    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.

    Best regards,
    Dillion

    3 people found this answer helpful.

4 additional answers

Sort by: Most helpful
  1. Pratham Jain 221 Reputation points
    2022-10-04T09:35:05.667+00:00

    Hi ZhiLv-MSFT,

    Many thanks for your response to my question. I have followed the same approach advised by you but receiving the below error in browser:

    error: SyntaxError: Unexpected token '%', "%PDF-1.4 %"... is not valid JSON at JSON.parse(

    Http failure during parsing for http://localhost:5157/api/downloadFile?filePath=2022\Aug\completed\27eagfh-cf32-5c3f-8d48-1231d2312dsdaCompleted.pdf"

    I am using the below code-

     public override async Task<ActionResult<string>> HandleAsync([FromQuery]string filePath, CancellationToken cancellationToken = default)  
                {  
                    try  
                    {  
                        var filePathWithName = "https://test-file-directory.mywebsite.com/" + filePath.Replace("\\", "/");  
                        var result = await _downloadService.GetUrlContent(filePathWithName);  
                        if (result != null)  
                        {  
                            return File(result, "APPLICATION/octet-stream", Path.GetFileName(filePath));  
                        }  
                        return Ok("file is not exist");  
                    }  
                    catch (Exception ex)  
                    {  
                        _logger.LogError(ex, $"Error while downloading the file");  
                        return StatusCode(StatusCodes.Status500InternalServerError);  
                        throw;  
                    }  
                }  
          
                public async Task<byte[]?> GetUrlContent(string url)  
                {  
                    using (var client = new HttpClient())  
                    using (var result = await client.GetAsync(url))  
                        return result.IsSuccessStatusCode ? await result.Content.ReadAsByteArrayAsync() : null;  
                }  
      
    

    Please advise if I am missing anything in above code.

    Thanks and Regards,
    Pratham Jain

    0 comments No comments

  2. Pratham Jain 221 Reputation points
    2022-10-04T09:43:16.97+00:00

    Hi @Zhi Lv - MSFT ,

    Many thanks for your response to my question. I have followed the same approach advised by you but receiving the below error in browser:

    error: SyntaxError: Unexpected token '%', "%PDF-1.4 %"... is not valid JSON at JSON.parse(

    Http failure during parsing for http://localhost:5157/api/downloadFile?filePath=2022\Aug\completed\27eagfh-cf32-5c3f-8d48-1231d2312dsdaCompleted.pdf"

    I am using the below code-

     public override async Task<ActionResult<string>> HandleAsync([FromQuery]string filePath, CancellationToken cancellationToken = default)  
                {  
                    try  
                    {  
                        var filePathWithName = "https://test-file-directory.mywebsite.com/" + filePath.Replace("\\", "/");  
                        var result = await _downloadService.GetUrlContent(filePathWithName);  
                        if (result != null)  
                        {  
                            return File(result, "APPLICATION/octet-stream", Path.GetFileName(filePath));  
                        }  
                        return Ok("file is not exist");  
                    }  
                    catch (Exception ex)  
                    {  
                        _logger.LogError(ex, $"Error while downloading the file");  
                        return StatusCode(StatusCodes.Status500InternalServerError);  
                        throw;  
                    }  
                }  
          
                public async Task<byte[]?> GetUrlContent(string url)  
                {  
                    using (var client = new HttpClient())  
                    using (var result = await client.GetAsync(url))  
                        return result.IsSuccessStatusCode ? await result.Content.ReadAsByteArrayAsync() : null;  
                }  
    

    Please advise if I am missing anything in above code.

    Thanks and Regards,
    Pratham Jain

    0 comments No comments

  3. Bruce (SqlWork.com) 61,731 Reputation points
    2022-10-05T17:19:01.55+00:00

    That looks like a client error. it appears the client is expecting a json response, not a binary stream.

    type the url in browser address bar. it should save the file. this will verify the server is correct.

    on the client side, you are probably using ajax and specific json response. not sure what you are typing to do client side, but you will need to use the blob datatype, and maybe fileapi

    0 comments No comments

  4. Krunal Patel 0 Reputation points
    2023-05-04T10:01:52.47+00:00

    I need the requirement to download a file using a web URL. I received a pdf file and a working file through the below code but some time pdf file is half blank and some of the content is blank.

    It's perfectly working in WebAPI code which is in .Net core but the same code and method is used in a console application. that is causing the issue.

    string PageURL="https://test.com/my-services/v1/maintenancereceipts/statement/pdf?AN=123";
    string fileName ="C:\\test\\API\\Upload\\123.pdf";
    
    if (!System.IO.File.Exists(fileName))
    {
        WebClient client = new WebClient();
        Thread.Sleep(1000);
        client.DownloadFile(url, fileName);
    }
    
    0 comments No comments