'Why is my file downloading only when I click retry .net core

I'm trying to export data from database to an excel file and then download that file on client side. The export works fine but the problem is with the download part. Every time I call the method "DownloadCurrent" I get failed attempt in the browser. But if I click on retry (circle arrow) in browser then it downloads the file with no problem. Code :

            ...
            string fileName = className + "Export.xlsx";
            string filePath = Directory.GetCurrentDirectory() + "\\wwwroot\\" + fileName;

        public void DownloadCurrent(String filePath, String fileName)
        {
            WebClient client = new WebClient();
            Byte[] buffer = client.DownloadData(filePath);
            if (buffer != null && buffer.Length > 0)
            {
                Response.ContentType = "application/vnd.ms-excel";
                Response.Headers.Add("content-length", buffer.Length.ToString());
                Response.Headers.Add("content-disposition", "attachment; filename=" + fileName);
                Response.Body.Write(buffer);
            }
        }

I'm using VS 2022, and .NET 6.0 ASP.NET Core Web App



Solution 1:[1]

As stated in a comment above, don't use WebClient anymore.

However, based on your code, you don't need to use either WebClient or HttpClient. It appears your file is a local file that you simply need to stream to the browser. The only reason I see that you would need to use a WebClient or HttpClient for this, is if that file needs to be first downloaded from a remote server via a URI, for example.

Something like this code should do the trick:

public void DownloadCurrent(String filePath, String fileName)
{
    using FileStream fs = File.OpenRead(filePath);
    long length = fs.Length;
    byte[] buffer = new byte[length];
    fs.Read(buffer, 0, (int)length);

    Response.ContentType = "application/vnd.ms-excel";
    Response.Headers.Add("content-length", length.ToString());
    Response.Headers.Add("content-disposition", "attachment; filename=" + fileName);
    Response.BinaryWrite(buffer);
}

For more, please see: https://docs.microsoft.com/en-us/dotnet/api/system.web.httpresponse.binarywrite?view=netframework-4.8.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matthew M.