Tuesday, November 30, 2010

Download Huge file using ASP.net from WCF Service

I was working with an ASP.net application which needs to download huge files (May be in GB’s too) from a WCF Service. Hence we decide to go with the WCF’s “Streaming” transfer mode to get the optimized performance. So all worked well. However the interesting piece was, how the streamed data will be pushed to the client browser as soon a new stream hit at the ASP.net server. If we push the file to the client ASAP at the same time that we get at the Server(ASP.Net), client may not have to wait for long to get his response. Not only that, the server memory will not be over used. If client start to see something happens , then he is happy too (at least he will get to know, something is happening inside the server.
Following was the approach that we finally reached.


try
{
// gets the stream from the WCF service.
iStream = WCF.GetLongFileStream();


// Total bytes to read:
dataToRead = iStream.Length;

Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

// 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 HTML output.
Response.Flush();

buffer= new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
// Trap the error, if any.
Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
Response.Close();
}

Ref: http://support.microsoft.com/kb/812406

No comments:

Post a Comment