I am using an async Action to download large files (>500MB). My below code hangs my application until the file download is complete.
public async Task<ActionResult> Download(string filePath, string fileName)
{
try
{
if(!string.IsNullOrEmpty(filePath))
{
filePath = Path.Combine(Code.Config.UploadFilesPath(), filePath);
string contentType = MimeMapping.GetMimeMapping(fileName);
if (System.IO.File.Exists(filePath))
{
await GetLargeFile(filePath, fileName);
}
else
{
return Content("Requested File does not exist");
}
}
}
catch(Exception ex) { }
return Content("");
}
private async Task GetLargeFile(string fullPath, string outFileName)
{
System.IO.Stream iStream = null;
// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];
// Length of the file:
int length;
// Total bytes to read:
long dataToRead;
// Identify the file to download including its path.
string filepath = fullPath;
// Identify the file name.
string filename = System.IO.Path.GetFileName(filepath);
try
{
// Open the file.
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;
Response.Clear();
Response.ContentType = MimeMapping.GetMimeMapping(filename);
Response.AddHeader("content-disposition", "attachment; filename=\"" + outFileName + "\"");
Response.AddHeader("Content-Length", iStream.Length.ToString());
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);
// Flush the data to the output.
Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
Response.Close();
}
}
It is strange that if I use the same code as above on a brand new Web application and download a large file (around 1GB), that application doesn't hang as I can switch between Views & trigger javascript alert function during download process.
But with my real project, application hangs until download is completed unfortunately.
Is there anything that I should consider in configs or anything else?
Any debugging tips to see how it is working on a brand new application but not on my actual project?