Asp.net| Multithreading
System.IO.Stream iStream = null;
Buffer to read 10K bytes in chunk:
byte[] buffer = new byte[10240];
Length of the file:
int length;
Total bytes to read:
Long dataToRead;
Identify the file to download including its path.
string filepath = @ "E:\software\SQL Server Personal Edition.iso";
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);
Response.Clear ();
Total bytes to read:
dataToRead = Istream.length;
Long p = 0;
if (request.headers["Range"]!=null)
{
Response.statuscode = 206;
p = long. Parse (request.headers["Range"). Replace ("bytes=", ""). Replace ("-", ""));
}
if (P!= 0)
{
Response.AddHeader ("Content-range", "bytes" + p.tostring () + "-" + ((long) (dataToRead-1)). ToString () + "/" + datatoread.tostring ());
}
Response.AddHeader ("Content-length", ((Long) (datatoread-p)). ToString ());
Response.ContentType = "Application/octet-stream";
Response.AddHeader ("Content-disposition", "attachment; Filename= "+ System.Web.HttpUtility.UrlEncode (Request.ContentEncoding.GetBytes (filename)));
Istream.position = p;
dataToRead = datatoread-p;
Read the bytes.
while (dataToRead > 0)
{
Verify That's the client is connected.
if (response.isclientconnected)
{
Read the data in buffer.
Length = istream.read (buffer, 0, 10240);
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[10240];
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.End ();
}