// Output the hard disk file for download
// Input parameter _ Request: Page. request object, _ Response: Page. response object, _ fileName: Download file name, _ fullPath: Download path with file name, _ speed bytes allowed to be downloaded per second
// Whether the response is successful
Public static bool ResponseFile (HttpRequest _ Request, HttpResponse _ Response, string _ fileName, string _ fullPath, long _ speed)
{
Try
{
FileStream myFile = new FileStream (_ fullPath, FileMode. Open, FileAccess. Read, FileShare. ReadWrite );
BinaryReader br = new BinaryReader (myFile );
Try
{
_ Response. AddHeader ("Accept-Ranges", "bytes ");
_ Response. Buffer = false;
Long fileLength = myFile. Length;
Long startBytes = 0;
Int pack = 10240; // 10 K bytes
// Int sleep = 200; // 5 times per second, that is, 5*10 K bytes per second
Int sleep = (int) Math. Floor (1000 * pack/_ speed) + 1;
If (_ Request. Headers ["Range"]! = Null)
{
_ Response. StatusCode = 206;
String [] range = _ Request. Headers ["Range"]. Split (new char [] {'= ','-'});
StartBytes = Convert. ToInt64 (range [1]);
}
_ Response. AddHeader ("Content-Length", (fileLength-startBytes). ToString ());
If (startBytes! = 0)
{
_ Response. AddHeader ("Content-Range", string. Format ("bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength ));
}
_ Response. AddHeader ("Connection", "Keep-Alive ");
_ Response. ContentType = "application/octet-stream ";
_ Response. AddHeader ("Content-Disposition", "attachment; filename =" + HttpUtility. UrlEncode (_ fileName, System. Text. Encoding. UTF8 ));
Br. BaseStream. Seek (startBytes, SeekOrigin. Begin );
Int maxCount = (int) Math. Floor (fileLength-startBytes)/pack) + 1;
For (int I = 0; I <maxCount; I ++)
{
If (_ Response. IsClientConnected)
{
_ Response. BinaryWrite (br. ReadBytes (pack ));
Thread. Sleep (sleep );
}
Else
{
I = maxCount;
}
}
}
Catch
{
Return false;
}
Finally
{
Br. Close ();
MyFile. Close ();
}
}
Catch
{
Return false;
}
Return true;
}
Call example
Page. Response. Clear ();
Bool success = ResponseFile (Page. Request, Page. Response, "filename", @ "C: \ download. date", 1024000 );
If (! Success)
Response. Write ("An error occurred while downloading the file! ");
Page. Response. End ();
In this way, the downloading is controllable, and the size of the file block to be read can be controlled. This effectively prevents theft and monitors the downloading of resources. If you can encapsulate it well, it will be a very powerful class. (Bai Ling said: I added this section myself. I am trying to encapsulate it. Thanks for Arhrun knowledge sharing, thanks)