1

My below API action is supposed to send a zip file (max 100mb) as the result. There are no errors thrown in the code, however the file downloaded is 0 size. I checked the content length and there is value in the content length. what could be the reason.

[HttpGet]
        [Route("AsyncDownloadFile")]
        public async Task<HttpResponseMessage> AsyncDownloadFile(int ModuleID, string LicenseKey, string Version)
        {
            try
            {
                ClientOutletsDAL co = new ClientOutletsDAL();
                //var localFilePath = "path/zz.zip"

                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));

                Stream streamToCopyTo= new MemoryStream();
                using (FileStream fs = new FileStream(localFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
                {
                     await fs.CopyToAsync(streamToCopyTo);
                }
                response.Content = new StreamContent(streamToCopyTo);
                //Set the Response Content Length.
                response.Content.Headers.ContentLength = streamToCopyTo.Length;
                response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = Path.GetFileName(localFilePath);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");

                return response;
            }

            catch (Exception ex)
            {
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message );
                return response;
            }
        }
Sin
  • 1,836
  • 2
  • 17
  • 24
  • 3
    I bet you have to reset stream position to 0 `streamToCopyTo` after you copied file stream – Irdis May 13 '20 at 13:06

2 Answers2

1

The issue was solved by adding

streamToCopyTo.Position = 0;

after

response.Content = new StreamContent(streamToCopyTo);
Sin
  • 1,836
  • 2
  • 17
  • 24
-1

I notice you have the following in your code

 new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));

but it is not used but it appears to be trying to open the same file so I wonder if you its a file share issue.

Also, do you have permissions for sure (just checking) and lastly, have you stepped through this code to verify that streamToCopyTo has data in it?

Cheers

M M E G
  • 24
  • 4