.NETC #: Implement the HTTP web client tool class for support breakpoints to renew multi-thread download (C # DIY HTTPWEBCLIENT)

xiaoxiao2021-03-06  15

/ * .NET / C #: Implement the HTTP web client tool class that supports breakpoints to renew multi-thread download (C # diy httpwebclient) * Reflector has a case of system.net.WebClient, rewriting, or adds a number of: * Download, Upload related methods ! * Download related changes! * Added DataReceive, ExceptionOccurrs event! * Understand the HTTP protocol of the server-side interaction with the client to see: * Let the file download custom connection support FlashGet breakpoint renewable multi-thread link download! JSP / Servlet implementation! * Http://blog.9cbs.net/playyueer/archive/2004/08/02/58430.aspx * Make the file download custom connection supports FlashGet breakpoint renewal multi-thread link download! C # / ASP.NET implementation! * Http://blog.9cbs.net/playyuer/archive/2004/08/02/58281.aspx * /

namespace Microshaoft.Utils {using System; using System.IO; using System.Net; using System.Text; using System.Security; using System.Threading; using System.Collections.Specialized; ///

/// recorded Download byte position /// public class downloadstate {private string _filename

Private string _ttachmentname; private int _position; private string _RequestURL; private string _responseurl; private int _length

Private byte [] _DATA;

Public string filename {get {return _filename;}}

Public int position {get {return _Position;}}

Public Int length {get {return _length;}}

Public string attachmentname {get {return _attachmentname;}}

Public String Requesturl {Get {Return_RequestURL;}}

Public string responseurl {get {return_responseurl;}}

Public Byte [] data {get {return_data;}}

internal DownLoadState (string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length, byte [] Data) {this._FileName = FileName; this._RequestURL = RequestURL; this._ResponseURL = ResponseURL; this._AttachmentName = AttachmentName ; this._Position = Position; this._Data = Data; this._Length = Length;} internal DownLoadState (string RequestURL, string responseURL, string FileName, string AttachmentName, int Position, int Length, ThreadCallbackHandler tch) {this._RequestURL = RequestURL THIS._RESPONSEURL = responseURL; this._filename = filename; this._attachmentname = attachmentname; this._position = position; this._ens = length; this._threadcallback = tch;}

internal DownLoadState (string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length) {this._RequestURL = RequestURL; this._ResponseURL = ResponseURL; this._FileName = FileName; this._AttachmentName = AttachmentName; this._Position = POSITION; this._length = length;}

Private threadCallbackHandler_threadcallback;

// INTERNAL VOID StartDownloadFilechunk () {if (this._threadcallback! = Null) {this._threadcallback (this._requesturl, this._filename, this._position, this._length);}}

}

/ / Enter the method of executing the proxy thread signing uniform public delegate Void ThreadCallbackHandler (String S, String S, INT I, INT i);

// Abnormal processing action public enum exceptionActions {throw, cacall, ignore, retry}

///

/// event data comprising Exception class /// public class ExceptionEventArgs: System.EventArgs {private System.Exception _Exception; private ExceptionActions _ExceptionAction; private DownLoadState _DownloadState;

Public DownloadState DownloadState {Get {Return_downloadState;}}

Public Exception Exception {get {return _exception;}}

PUBLIC EXCETIONACTIONES EXCETIONACTION {Get {Return _ExceptionAction;} set {_exceptionAction = value;}}

INTERNAL EXCEPTIONEVENTARGS (System.Exception E, DownloadState DownloadState) {this._exception = E; this._downloadstate = DownloadState;}}

///

/// includes a class /// public class downloadeventArgs: system.eventargs {private design;

Public DownloadState DownloadState {Get {Return_downloadState;}}

Public DownloadState {THIS._DOWNLOADSTATATE = DownloadState;

}

///

/// Support breakpoint to renew multi-thread download class /// public class httpwebclient {private static object _synclockObject = new object ();

Public Delegate Void DataReceiveEventHandler (HttpWebClient Sender, DownloadEventAndargs E);

Public Event DataReceiveEventHandler DataReceive; // Receive Byte Data Event

Public Delegate Void ExceptionEventHandler (HttpWebClient Sender, ExceptionEventArgs E);

Public Event ExceptionEventHandler ExceptionOccurrs; // A abnormal event occurs

Private int _fileLength; // Download the total size of the file

Public int filelength {get {return _fileLength;}}

///

/// 分 块 下载 下载 /// /// URL address /// Save to Local path file name /// number, number of threads public void Downloadfile (String address, string filename, int chunkscount) {int P = 0; // position int s = 0; // chunk size string a = null; HttpWebRequest hwrq; HttpWebResponse hwrp = null; try {hwrq = (HttpWebRequest) WebRequest.Create (this.GetUri (Address)); hwrp = (HttpWebResponse) hwrq.GetResponse (); Long l = hwrp.contentLength; hwrq.credentials = this.m_credentials;

L = ((l == -1) || (L> 0x7fffffff))? ((Long) 0x7fffffff): L; //int32.maxvalue This constant is 2,147,483,647; ie hexadecimal 0x7fffffffFFFFFFFFFFFFFFFFFF

INT L = (int) L;

THIS._FILENGTH = L;

// In the local predetermined space (actually do not have a predetermined space in multi-thread) // filestream sw = new filestream (filename, filemode.openorcreate, fileaccess.readwrite, fileshare.readwrite); // sw.write (New Byte [L ], 0, l); // sw.close (); // SW = NULL;

Bool B = (hwrp.headers]! = null & hwrp.headers ["accept-ranges"] == "bytes"); a = hwrp.headers ["content-disposition"]; //// Attachment if (a! = null) {a = a.substring (a.lastIndexof ("filename =") 9);} else {a = filename;}

INT SS = S; IF (b) {s = l / chunkscount; if (S <2 * 64 * 1024) // block size is at least 128 k byte {s = 2 * 64 * 1024;} ss = s; INT i = 0; While (L> S) {L - = S; if (l 0) {DownloadState X = New DownloadState (address, hwrp.responseuri.absolutePath , FileName, a, p, s, new ThreadCallbackHandler (this.DownloadFileChunk)); // threaded download // x.StartDownloadFileChunk (); // multithreaded download // thread t = new thread (new ThreadStart (x.StartDownloadFileChunk ))))). START (); //t.Start ();} p = s;} s = ss; byte [] buffer = this.Responseasbytes (Address, HWRP, S, FileName);

// lock (_SyncLockObject) // {// this._Bytes = buffer.Length; //}}} catch (Exception e) {ExceptionActions ea = ExceptionActions.Throw; if (! This.ExceptionOccurrs = null) {DownLoadState x = new DownLoadState (Address, hwrp.ResponseUri.AbsolutePath, FileName, a, p, s); ExceptionEventArgs eea = new ExceptionEventArgs (e, x); ExceptionOccurrs (this, eea); ea = eea.ExceptionAction;}

IF (EA == ExceptionActions.throw) {if (! (e is webexception) &&! ("net_webclient", e);} throw;}}

}

///

/// Download a file block, using this method to implement multi-line comparison points /// /// URL address /// Saved to local path file name /// block size public void Downloadfilechunk (String Address, String FileName, int FromPosition, int Length) {HttpWebResponse hwrp = null; string a = null; try {//this._FileName = FileName; HttpWebRequest hwrq = (HttpWebRequest) WebRequest.Create (this.GetUri (Address)); //hwrq.Credentials = HWRQ.AddRedentials; hwrq.addrange (hwrp = (httpwebresponse) hwrq.getResponse (); a = hwrp.headers ["content-disposition"]; // attachment if (a! = null) {a = a. Substring ("FileName =") 9);} else {a = filename;} byte [] buffer = this.responseasbytes (address, hwrp, length, filename); // Lock (_SyncLockObject) // { // this._bytes = buffer.length; ///}} catch (exception e) {exceptionactions ea = exceptionactions.throw; if (this.ExceptionOccurrs = null!) {DownLoadState x = new DownLoadState (Address, hwrp.ResponseUri.AbsolutePath, FileName, a, FromPosition, Length); ExceptionEventArgs eea = new ExceptionEventArgs (e, x); ExceptionOccurrs (this, eea) EA = eea.exception;

IF (EA == ExceptionActions.throw) {if (! (e is webexception) &&! ("Net_WebClient", E);} through;}}}

INTERNAL BYTE [] Responseasbytes (String Requesturl, WebResponse Response, long length, string filename) {string a = null; // attachmentname int P = 0; // The position pointer of the entire file INT NUM2 = 0; Try {a = response. Headers ["Content-Disposition"]; // attachment if (a! = Null) {a = a.substring (a.lastIndexof ("filename =") 9);} long Num1 = length; //Response.contentLENGTH Bool flag1 = false; if (Num1 == -1) {flag1 = true; Num1 = 0x10000; // 64k} byte [] buffer1 = new byte [(int) Num1];

INT P = 0; // This block of position pointer

String s = response.Headers ["content-range"]; if (s! = null) {s = s.replace ("bytes", "); s = s.substring (0, s.indexof) ")); P = convert.toint32 (s);} int Num3 = 0;

Stream S = response.getResponseSstream (); do {Num2 = S. Read (Buffer1, Num3, ((int) Num1) - Num3);

Num3 = Num2; IF (Flag1 && (Num3 == Num1)) {Num1 = 0x10000; Byte [] Buffer2 = New Byte [(int) Num1]; buffer.blockcopy (buffer1, 0, buffer2, 0, num3) Buffer1 = buffer2;}

// Lock (_SyncLockObject) // {// this._bytes = Num2; //} f (Num2> 0) {if (this.DataReceive! = Null) {byte [] buffer = new byte [Num2]; buffer .BlockCopy (buffer1, p, buffer, 0, buffer.Length); DownLoadState dls = new DownLoadState (RequestURL, Response.ResponseUri.AbsolutePath, FileName, a, P, num2, buffer); DownLoadEventArgs dlea = new DownLoadEventArgs (dls); // Trigger event this.ondatareceive (DLEA); //system.threading.thread.sleep(100);} P = Num2; // This block position pointer P = Num2; // The position pointer of the entire file} Else {Break;

} While (Num2! = 0);

S.close (); s = null; if (flag1) {byte [] buffer3 = new byte [Num3]; buffer1, 0, buffer3, 0, num 3); buffer1 = buffer3;} return buffer1;} catch (Exception e) {ExceptionActions ea = ExceptionActions.Throw; if (! this.ExceptionOccurrs = null) {DownLoadState x = new DownLoadState (RequestURL, Response.ResponseUri.AbsolutePath, FileName, a, P, num2); ExceptionEventArgs eea = new ExceptionEventArgs (E, X); Exceptionocurrs (this, EEA); EA = EEA.Exception;

IF (EA == ExceptionActions.throw) {if (! (e is webexception) &&! ("Net_WebClient", E);} throw;}}}}}}} Return NULL

Private void OnDataReceive (DownloadEventArgs E) {// Trigger data arrival event DataReceive (this, e);}

Public Byte [] UPLOADFILE (STRING Address, String FileName) {Return this.uploadFile (Address, "Post", FileName, "File");}

public string UploadFileEx (string address, string method, string fileName, string fieldName) {return Encoding.ASCII.GetString (UploadFile (address, method, fileName, fieldName));} public byte [] UploadFile (string address, string method, string FileName, String FieldName) {byte [] buffer4; filestream stream1 = null; try {filename = path.getFullPath (filename); string text1 = "----------------- - " DateTime.now.ticks.tostring (" x ");

String text2 = "Application / OcTet-stream";

stream1 = new FileStream (fileName, FileMode.Open, FileAccess.Read); WebRequest request1 = WebRequest.Create (this.GetUri (address)); request1.Credentials = this.m_credentials; request1.ContentType = "multipart / form-data; Boundary = " Text1;

Request1.method = method; string [] textArray1 = new string [7] {"-", text1, "/ r / ncontent-disposition: form-data; name = /" fieldname "/"; filename = / "" ", Path.getfilename (filename)," / "/" / r / nContent-type: ", text2," / r / n / r / n "}; string text3 = string.concat (TextArray1); byte [] Buffer1 = encoding.utf8.getbytes (text3); byte [] buffer2 = encoding.ascii.getbytes ("/ r / n" text1 "/ r / n"); long Num1 = 0x7fffffffffffffffff; Try {Num1 = Stream1.Length; Request1.contentLength = (Num1 Buffer1.Length) Buffer2.Length;} catch {} byte [] buffer3 = new byte [Math.min (0x2000, (int) Num1)]; use)]; use)]; using (stream stream2 = Request1.getRequestStream ()) {Int Num2; stream2.write (buffer1, 0, buffer1.Length); do {Num2 = stream1.read (buffer3, 0, buffer3.length); if (Num2! = 0) {stream2. Write (Buffer3, 0, Num2);}} while (Num2! = 0); stream2.write (buffer2, 0, buffer2.Length);} stream1.close (); stream1 = Null; WebResponse response1 = request1.GetResponse (); buffer4 = this.ResponseAsBytes (response1);} catch (Exception exception1) {if (stream1 = null!) {Stream1.Close (); stream1 = null;} if (! (exception1 is WebException) && (exception1 is SecurityException)) {// throw new WebException (SR.GetString ( "net_webclient"), exception1); throw new WebException ( "net_webclient", exception1);}! throw;} return buffer4; }

private byte [] ResponseAsBytes (WebResponse response) {int num2; long num1 = response.ContentLength; bool flag1 = false; if (num1 == -1) {flag1 = true; num1 = 0x10000;} byte [] buffer1 = new byte [(int) Num1]; stream stream1 = response.getResponseSstream (); int Num3 = 0; do {Num2 = stream1.read (buffer1, num3, ((int) Num1) - Num3); Num3 = Num2; IF Flag1 && (Num3 == Num1)) {Num1 = 0x10000; Byte [] Buffer2 = New Byte [(int) Num1]; Buffer.Blockcopy (Buffer1, 0, Buffer2, 0, Num3); buffer1 = buffer2;}}} While (Num2! = 0); stream1.close (); if (flag1) {byte [] buffer3 = new byte [Num3]; buffer1, 0, buffer3, 0, num3); buffer1 = buffer3;} Return buffer1;} private namevaluecollection m_requestparameters; private uri m_baseaddress; private icredentials m_credentials = credentialcache.defaultcredentials;

Public ictedentials credentials {get {returnim_credentials;} set {this.m_credentials = value;

public NameValueCollection QueryString {get {if (this.m_requestParameters == null) {this.m_requestParameters = new NameValueCollection ();} return this.m_requestParameters;} set {this.m_requestParameters = value;}}

Public string baseaddress {get {if (this.m_baseaddress! = null) {returnim_baseaddress.tostring ();} return string.empty;} set {i ((value == null) || (value.length == 0)) {this.m_baseAddress = null;} else {try {this.m_baseAddress = new Uri (value);} catch (Exception exception1) {throw new ArgumentException ( "value", exception1);}}}} private Uri getUri (string path) {URI URI1; Try {if (this.m_baseaddress! = null) {uri1 = new URI (this.m_baseaddress, path);} else {uri1 = new URI (PATH);} IF (this.m_requestparameters = = null) {return uri1;} StringBuilder builder1 = new StringBuilder (); string text1 = string.Empty; for (int num1 = 0; num1

}

}

///

/// Test class /// class appteest {static void main () {apptest a = new apptest (); microshaoft.utils.httpwebclient x = new microshaoft.utils.httpwebclient () ;

// Subscribe DataReceive event x.DataReceive = new Microshaoft.Utils.HttpWebClient.DataReceiveEventHandler (a.x_DataReceive); // subscribe ExceptionOccurrs event x.ExceptionOccurrs = new Microshaoft.Utils.HttpWebClient.ExceptionEventHandler (a.x_ExceptionOccurrs); string F = "http://localhost/download/phpmyadmin-2.6.1-pl2.zip"; A._F = f; f = "http://localhost/download/jdk-1_5_0_01-windows-i586-p.aa. EXE "; // f =" http://localhost/download/resharper1.5.exe ";

// f = "http://localhost/mywebapplications/webapplication7/webform1.aspx"; // f = "http: // localhost: 1080 / test / demary.jsp";

// f = "http://localhost/download/webcast20050125_ppt.zip"; // f = "http://www.morequick.com/greenbrowsergb.zip"; // f = "http: // localhost / download / Test_local.rar "; string f = f.substring (f.lastIndexof (" / ") 1);

// (New System.Threading.Thread (New System.Threading.ThreadStart (New ThreadProcessState (f, @ "E: / TEMP /" F, 10, x) .startthreadProcess))))))). Start ();

x.downloadfile (f, @ "e: / temp / temp /" f, 10); // x.downloadfilechunk (f, @ "E: / TEMP /" F, 15, 34556);

System.console.readline (); // upload test // String UploadFile = "E: //test_local.rar"; // string str = x.uploadfileex ("http://localhost/phpmyadmin/uploadAction.php", "POST", UPLOADFILE, "File1"); // system.console.writeline (STR); // system.console.readline ();}

String BS = ""; // Used to record the last bit number BOOL B = false; private int i = 0; private static object _synclockObject = new object (); string _f; string _f;

private void x_DataReceive (Microshaoft.Utils.HttpWebClient Sender, Microshaoft.Utils.DownLoadEventArgs e) {if (! this.b) {lock (_SyncLockObject) {if (! this.b) {System.Console.Write (System.DateTime. Now.toTString () "has received data:"); //system.console.write (system.datetime.now.tostring () "has received data:"); this.b = true;}} F = E.DownloadState.FileName; if (e.downloadstate.attachmentName! = null) f = system.io.path.getdirectoryName (f) @ "/" E.DownloadState.attachmentName; this._f = f;

Using (System.IO.FileStream SW = New System.io.FileStream (f, system.io.filemode.openorcreate, system.io.filecess.readwrite, system.io.fileshare.readwrite) {sw.position = e. DownloadState.position; sw.write (E.DownloadState.Data, 0, E.DownloadState.Data.Length); sw.close ();} string s = system.datetime.now.tostring (); lock.tostring (); lock.tockObject THIS.I = E.DownloadState.Data.Length; System.Console.write (BS "/ B / B / B / B / B / B / B / B / B / B / B" i "/" Sender.fileLength "byte data" s); //system.console.write (BS i "byte data" s); this.bs = new string ('/ b', DIGITS (i) 3 Digits (Sender.FileLength) S.Length);}}

INT DIGITS (INT N) // Number of places {n = system.math.abs (n = n / 10; int i = 1; while (n> 0) {n = N / 10; i } Return i;}

private void x_ExceptionOccurrs (Microshaoft.Utils.HttpWebClient Sender, Microshaoft.Utils.ExceptionEventArgs e) {System.Console.WriteLine (e.Exception.Message); corresponds to an abnormal re-download HTTP // happens, you can choose their own treatment or the discretion Microshaoft.Utils.HttpWebClient x = new Microshaoft.Utils.HttpWebClient (); x.DownloadFileChunk (this._F, this._f, e.DownloadState.Position, e.DownloadState.Length); e.ExceptionAction = Microshaoft.Utils.exceptionActions.ignore;}} / * * Action php: http://localhost/phpmyadmin/uploadAction.php: new document </ title> </ head> <body> <? Php print_r ($ _ request); $ uploaddir = ''; $ uploadfile = $ uploaddir. $ _Files [ 'file1'] ['Name']; Print "<pre>"; if (Move_uploaded_file ($ _ files ['file1'] ['TMP_NAME'], $ UPLOADFILE)) {Print "File is Valid, and Was successfully uploaded. "} Else {print" Possible File Upload Attack! Here's Some Debugging Info: / N "; Print_r ($ _ files);} print" </ pre> ";?> </ Body> </ html> * / 2005- 03 -14 Revision:</p> <p>/ * .NET / C #: Implement the tool class for the breakpoint to renew multi-thread downloads * Reflector has a slice of system.Net.WebClient, overloaded or adds a number of: * Download, Upload related methods! * Added DataReceive, ExceptionOccurrs event * /</p> <p>Namespace microshaoft.utils {using system; using system.net; using system.text; using system.threading; using system.chreading; using system.collections.specialize;</p> <p>/// <summary> /// Record download byte location /// </ summary> public class downloadState {private string _filename;</p> <p>Private string _ttachmentname; private int _position; private string _RequestURL; private string _responseurl; private int _Length; private bote [] _data</p> <p>Public string filename {get {return _filename;}}</p> <p>Public int position {get {return _Position;}}</p> <p>Public Int length {get {return _length;}}</p> <p>Public string attachmentname {get {return _attachmentname;}}</p> <p>Public String Requesturl {Get {Return_RequestURL;}}</p> <p>Public string responseurl {get {return_responseurl;}}</p> <p>Public Byte [] data {get {return_data;}}</p> <p>internal DownLoadState (string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length, byte [] Data) {this._FileName = FileName; this._RequestURL = RequestURL; this._ResponseURL = ResponseURL; this._AttachmentName = AttachmentName "This._position = position; this._data = data; THIS._LENGTH = Length;}</p> <p>internal DownLoadState (string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length, ThreadCallbackHandler tch) {this._RequestURL = RequestURL; this._ResponseURL = ResponseURL; this._FileName = FileName; this._AttachmentName = AttachmentName; this ._Position = position; this._gength = length; this._threadcallback = tch;}</p> <p>internal DownLoadState (string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length) {this._RequestURL = RequestURL; this._ResponseURL = ResponseURL; this._FileName = FileName; this._AttachmentName = AttachmentName; this._Position = Position; this._length = length;} private threadcallback;</p> <p>Public httpwebclient httpwebclient {get {return this._hwc;} set {tHIS._HWC = value;}}</p> <p>INTERNAL THREAD THREAD {Get {Return_thread;} ​​set {_thread = value;}}</p> <p>Private httpwebclient _hwc; private thread _thread;</p> <p>// internal void StartDownloadFileChunk () {if (this._ThreadCallback = null!) {This._ThreadCallback (this._RequestURL, this._FileName, this._Position, this._Length); this._hwc.OnThreadProcess (this._thread); }</p> <p>}</p> <p>/ / Enter the method of executing the proxy thread signing uniform public delegate Void ThreadCallbackHandler (String S, String S, INT I, INT i);</p> <p>// Abnormal processing action public enum exceptionActions {throw, cacall, ignore, retry}</p> <p>/// <summary> /// contains Exception event data class /// </ summary> public class exceptionEventArgs: system.eventargs {private system.exception_exception; private exceptionAnch_exception;</p> <p>Private DownloadState_downloadstate;</p> <p>Public DownloadState DownloadState {Get {Return_downloadState;}}</p> <p>Public Exception Exception {get {return _exception;}}</p> <p>PUBLIC EXCETIONACTIONES EXCETIONACTION {Get {Return _ExceptionAction;} set {_exceptionAction = value;}}</p> <p>internal ExceptionEventArgs (System.Exception e, DownLoadState DownloadState) {this._Exception = e; this._DownloadState = DownloadState;}} /// <summary> /// DownLoad comprising event data such /// </ summary> public class DownloadEventArgs: system.eventargs {private downloadState_downloadstate;</p> <p>Public DownloadState DownloadState {Get {Return_downloadState;}}</p> <p>Public DownloadState {THIS._DOWNLOADSTATATE = DownloadState;</p> <p>}</p> <p>Public Class ThreadProcessEventArgs: system.eventargs {private thread_thread;</p> <p>Public thread thread {get {return this._thread;}}</p> <p>Public ThreadProcessEventArgs (thread thread) {this._thread = thread;</p> <p>}</p> <p>/// <summary> /// Support breakpoint to renew multi-thread download class /// </ summary> public class httpwebclient {private static object _synclockObject = new object ();</p> <p>Public Delegate Void DataReceiveEventHandler (HttpWebClient Sender, DownloadEventAndargs E);</p> <p>Public Event DataReceiveEventHandler DataReceive; // Receive Byte Data Event</p> <p>Public Delegate Void ExceptionEventHandler (HttpWebClient Sender, ExceptionEventArgs E);</p> <p>Public Event ExceptionEventHandler ExceptionOccurrs; // A abnormal event occurs</p> <p>Public Delegate Void ThreadProcessEventHandler (HttpwebClient Sender, ThreadProcessEventArgs E);</p> <p>Public Event ThreadProcessEventHandler ThreadProcessend; // Multi-threaded tension event</p> <p>Private int _fileLength; // Download the total size of the file</p> <p>Public int filelength {get {return _fileLength;}}</p> <p>/// <summary> /// 分 块 下载 下载 /// </ summary> /// <param name = "address"> URL address </ param> /// <param name = "fileename"> Save to Local path file name </ param> /// <param name = "chunkscount"> number, number of threads </ param> public void Downloadfile (String address, string filename, int chunkscount) {int P = 0; // position int s = 0; // chunk size string a = null; HttpWebRequest hwrq; HttpWebResponse hwrp = null; try {hwrq = (HttpWebRequest) WebRequest.Create (this.GetUri (Address)); hwrp = (HttpWebResponse) hwrq.GetResponse (); Long l = hwrp.contentLength; hwrq.credentials = this.m_credentials;</p> <p>L = ((l == -1) || (L> 0x7fffffff))? ((Long) 0x7fffffff): L; //int32.maxvalue This constant is 2,147,483,647; ie hexadecimal 0x7fffffffFFFFFFFFFFFFFFFFFF</p> <p>INT L = (int) L;</p> <p>THIS._FILENGTH = L;</p> <p>// In the local predetermined space (actually do not have a predetermined space in multi-thread) // filestream sw = new filestream (filename, filemode.openorcreate, fileaccess.readwrite, fileshare.readwrite); // sw.write (New Byte [L ], 0, l); // sw.close (); // SW = NULL;</p> <p>Bool B = (hwrp.headers]! = null & hwrp.headers ["accept-ranges"] == "bytes"); a = hwrp.headers ["content-disposition"]; //// Attachment if (a! = null) {a = a.substring (a.lastIndexof ("filename =") 9);} else {a = filename;}</p> <p>INT SS = S; IF (b) {s = l / chunkscount; if (S <2 * 64 * 1024) // block size is at least 128 k byte {s = 2 * 64 * 1024;} ss = s; INT i = 0; While (L> S) {L - = S; if (l <s) {s = L;} if (i > 0) {DownloadState X = New DownloadState (address, hwrp.responseuri.absolutePath , FileName, a, p, s, new ThreadCallbackHandler (this.DownloadFileChunk)); // threaded download // x.StartDownloadFileChunk (); x.httpWebClient = this; // multithreaded download thread t = new thread (new ThreadStart (x.startdownloadfilechunk); //this.ontreadprocess (T.Start ();</p> <p>} P = s;} s = ss; byte [] buffer = this.Responseasbytes (Address, HWRP, S, FileName); this.ontreadProcess (thread.currentthread);</p> <p>// lock (_SyncLockObject) // {// this._Bytes = buffer.Length; //}}} catch (Exception e) {ExceptionActions ea = ExceptionActions.Throw; if (! This.ExceptionOccurrs = null) {DownLoadState x = new DownLoadState (Address, hwrp.ResponseUri.AbsolutePath, FileName, a, p, s); ExceptionEventArgs eea = new ExceptionEventArgs (e, x); ExceptionOccurrs (this, eea); ea = eea.ExceptionAction;}</p> <p>IF (EA == ExceptionActions.throw) {if (! (e is webexception) &&! ("net_webclient", e);} throw;}}</p> <p>}</p> <p>Internal Void OnthreadProcess (ThreadProcessend! = null) {ThreadProcessEventArgs TPEA = New ThreadProcessEventArgs (T); ThreadProcessend (THIS, TPEA);}}</p> <p>/// <summary> /// Download a file block, using this method to implement multi-line comparison points /// </ summary> /// <param name = "address"> URL address </ param> /// <param name = "filename"> Saved to local path file name </ param> /// <param name = "length"> block size </ param> public void Downloadfilechunk (String Address, String FileName, int FromPosition, int Length) {HttpWebResponse hwrp = null; string a = null; try {//this._FileName = FileName; HttpWebRequest hwrq = (HttpWebRequest) WebRequest.Create (this.GetUri (Address)); //hwrq.Credentials = HWRQ.AddRedentials; hwrq.addrange (hwrp = (httpwebresponse) hwrq.getResponse (); a = hwrp.headers ["content-disposition"]; // attachment if (a! = null) {a = a. Substring (A.lastIndexof ("FileName =") 9);} else {a = filename;}</p> <p>BYTE [] Buffer = this.responseasbytes (address, hwrp, length, filename); // Lock (_SyncLockObject) // {// this._bytes = buffer.length; //}} catch (Exception E) {ExceptionActions EA = ExceptionActions.Throw; if (! this.ExceptionOccurrs = null) {DownLoadState x = new DownLoadState (Address, hwrp.ResponseUri.AbsolutePath, FileName, a, FromPosition, Length); ExceptionEventArgs eea = new ExceptionEventArgs (e, x); ExceptionOccurrs (this, EEA); EA = EEA.Exception;</p> <p>IF (EA == ExceptionActions.throw) {if (! (e is webexception) &&! ("Net_WebClient", E);} through;}}}</p> <p>INTERNAL BYTE [] Responseasbytes (String Requesturl, WebResponse Response, long length, string filename) {string a = null; // attachmentname int P = 0; // The position pointer of the entire file INT NUM2 = 0; Try {a = response. Headers ["Content-Disposition"]; // attachment if (a! = Null) {a = a.substring (a.lastIndexof ("filename =") 9);} long Num1 = length; //Response.contentLENGTH Bool flag1 = false; if (Num1 == -1) {flag1 = true; Num1 = 0x10000; // 64k} byte [] buffer1 = new byte [(int) Num1];</p> <p>INT P = 0; // This block of position pointer</p> <p>String s = response.Headers ["content-range"]; if (s! = null) {s = s.replace ("bytes", "); s = s.substring (0, s.indexof) ")); P = convert.toint32 (s);} int Num3 = 0;</p> <p>Stream S = response.getResponseSstream (); do {Num2 = S. Read (Buffer1, Num3, ((int) Num1) - Num3);</p> <p>Num3 = Num2; IF (Flag1 && (Num3 == Num1)) {Num1 = 0x10000; Byte [] Buffer2 = New Byte [(int) Num1]; buffer.blockcopy (buffer1, 0, buffer2, 0, num3) Buffer1 = buffer2;}</p> <p>// Lock (_SyncLockObject) // {// this._bytes = Num2; //} f (Num2> 0) {if (this.DataReceive! = Null) {byte [] buffer = new byte [Num2]; buffer .BlockCopy (buffer1, p, buffer, 0, buffer.Length); DownLoadState dls = new DownLoadState (RequestURL, Response.ResponseUri.AbsolutePath, FileName, a, P, num2, buffer); DownLoadEventArgs dlea = new DownLoadEventArgs (dls); // Trigger event this.ondatareceive (DLEA); //system.threading.thread.sleep(100);} P = Num2; // This block position pointer P = Num2; // The position pointer of the entire file} Else {Break;</p> <p>} While (Num2! = 0);</p> <p>S.close (); s = null; if (flag1) {byte [] buffer3 = new byte [Num3]; buffer1, 0, buffer3, 0, num 3); buffer1 = buffer3;} return buffer1;} catch (Exception e) {ExceptionActions ea = ExceptionActions.Throw; if (! this.ExceptionOccurrs = null) {DownLoadState x = new DownLoadState (RequestURL, Response.ResponseUri.AbsolutePath, FileName, a, P, num2); ExceptionEventArgs eea = new ExceptionEventArgs (E, X); Exceptionocurrs (this, EEA); EA = EEA.Exception;</p> <p>IF (EA == ExceptionActions.throw) {if (! (e is webexception) &&! ("Net_WebClient", E);} throw;}}}}}}} Return NULL</p> <p>Private void OnDataReceive (DownloadEventArgs E) {// Trigger data arrival event DataReceive (this, e);}</p> <p>Public Byte [] UPLOADFILE (STRING Address, String FileName) {Return this.uploadFile (Address, "Post", FileName, "File");}</p> <p>public string UploadFileEx (string address, string method, string fileName, string fieldName) {return Encoding.ASCII.GetString (UploadFile (address, method, fileName, fieldName));} public byte [] UploadFile (string address, string method, string FileName, String FieldName) {byte [] buffer4; filestream stream1 = null; try {filename = path.getFullPath (filename); string text1 = "----------------- - " DateTime.now.ticks.tostring (" x ");</p> <p>String text2 = "Application / OcTet-stream";</p> <p>stream1 = new FileStream (fileName, FileMode.Open, FileAccess.Read); WebRequest request1 = WebRequest.Create (this.GetUri (address)); request1.Credentials = this.m_credentials; request1.ContentType = "multipart / form-data; Boundary = " Text1;</p> <p>Request1.method = method; string [] textArray1 = new string [7] {"-", text1, "/ r / ncontent-disposition: form-data; name = /" fieldname "/"; filename = / "" ", Path.getfilename (filename)," / "/" / r / nContent-type: ", text2," / r / n / r / n "}; string text3 = string.concat (TextArray1); byte [] Buffer1 = encoding.utf8.getbytes (text3); byte [] buffer2 = encoding.ascii.getbytes ("/ r / n" text1 "/ r / n"); long Num1 = 0x7fffffffffffffffff; Try {Num1 = Stream1.Length; Request1.contentLength = (Num1 Buffer1.Length) Buffer2.Length;} catch {} byte [] buffer3 = new byte [Math.min (0x2000, (int) Num1)]; use)]; use)]; using (stream stream2 = Request1.getRequestStream ()) {Int Num2; stream2.write (buffer1, 0, buffer1.Length); do {Num2 = stream1.read (buffer3, 0, buffer3.length); if (Num2! = 0) {stream2. Write (Buffer3, 0, Num2);}} while (Num2! = 0); stream2.write (buffer2, 0, buffer2.Length);} stream1.close (); stream1 = Null; WebResponse response1 = request1.GetResponse (); buffer4 = this.ResponseAsBytes (response1);} catch (Exception exception1) {if (stream1 = null!) {Stream1.Close (); stream1 = null;} if (! (exception1 is WebException) && (exception1 is SecurityException)) {// throw new WebException (SR.GetString ( "net_webclient"), exception1); throw new WebException ( "net_webclient", exception1);}! throw;} return buffer4; }</p> <p>private byte [] ResponseAsBytes (WebResponse response) {int num2; long num1 = response.ContentLength; bool flag1 = false; if (num1 == -1) {flag1 = true; num1 = 0x10000;} byte [] buffer1 = new byte [(int) Num1]; stream stream1 = response.getResponseSstream (); int Num3 = 0; do {Num2 = stream1.read (buffer1, num3, ((int) Num1) - Num3); Num3 = Num2; IF Flag1 && (Num3 == Num1)) {Num1 = 0x10000; Byte [] Buffer2 = New Byte [(int) Num1]; Buffer.Blockcopy (Buffer1, 0, Buffer2, 0, Num3); buffer1 = buffer2;}}} While (Num2! = 0); stream1.close (); if (flag1) {byte [] buffer3 = new byte [Num3]; buffer1, 0, buffer3, 0, num3); buffer1 = buffer3;} Return buffer1;} private namevaluecollection m_requestparameters; private uri m_baseaddress; private icredentials m_credentials = credentialcache.defaultcredentials;</p> <p>Public ictedentials credentials {get {returnim_credentials;} set {this.m_credentials = value;</p> <p>public NameValueCollection QueryString {get {if (this.m_requestParameters == null) {this.m_requestParameters = new NameValueCollection ();} return this.m_requestParameters;} set {this.m_requestParameters = value;}}</p> <p>Public string baseaddress {get {if (this.m_baseaddress! = null) {returnim_baseaddress.tostring ();} return string.empty;} set {i ((value == null) || (value.length == 0)) {this.m_baseAddress = null;} else {try {this.m_baseAddress = new Uri (value);} catch (Exception exception1) {throw new ArgumentException ( "value", exception1);}}}} private Uri getUri (string path) {URI URI1; Try {if (this.m_baseaddress! = null) {uri1 = new URI (this.m_baseaddress, path);} else {uri1 = new URI (PATH);} IF (this.m_requestparameters = = null) {return uri1;} StringBuilder builder1 = new StringBuilder (); string text1 = string.Empty; for (int num1 = 0; num1 <this.m_requestParameters.Count; num1 ) {builder1.Append (text1 this.m_requestParameters .Allkeys [Num1] "=" this.m_requestparameters [Num1]); Text1 = "&";} Uribuilder Bui Lder2 = New Uribuilder (URI1); Builder2.Query = Builder1.toString (); URI1 = Builder2.uri;} catch (uriformatexception) {URI1 = New URI (path.getFullPath (PATH));} Return Uri1;}</p> <p>}</p> <p>}</p> <p>/// <summary> /// Test class /// </ summary> class appteest {int _K = 0; int _k = 0;</p> <p>Static void main () {apptest a = new apptest (); microshaoft.utils.httpwebclient x = new microshaoft.utils.httpwebclient ();</p> <p>A._K = 10;</p> <p>// Subscribe DataReceive event x.DataReceive = new Microshaoft.Utils.HttpWebClient.DataReceiveEventHandler (a.x_DataReceive); // subscribe ExceptionOccurrs event x.ExceptionOccurrs = new Microshaoft.Utils.HttpWebClient.ExceptionEventHandler (a.x_ExceptionOccurrs); x. ThreadProcessEnd = new Microshaoft.Utils.HttpWebClient.ThreadProcessEventHandler (a.x_ThreadProcessEnd); string F = "http: //localhost/download/phpMyAdmin-2.6.1-pl2.zip"; a._F = F; F = "http : //localhost/download/jdk-1_5_0_01-windows-i586-p.aa.exe "; // f =" http://localhost/download/resharper1.5.exe ";</p> <p>// f = "http://localhost/mywebapplications/webapplication7/webform1.aspx"; // f = "http: // localhost: 1080 / test / demary.jsp";</p> <p>// f = "http://localhost/download/webcast20050125_ppt.zip"; // f = "http://www.morequick.com/greenbrowsergb.zip"; // f = "http: // localhost / download / Test_local.rar "; string f = f.substring (f.lastIndexof (" / ") 1);</p> <p>// (New System.Threading.Thread (New System.Threading.ThreadStart (New ThreadProcessState (f, @ "E: / TEMP /" F, 10, x) .startthreadProcess))))))). Start ();</p> <p>X.Downloadfile (f, @ "E: / TEMP / TEMP /" F, A._K); // x.downloadfilechunk (f, @ "E: / TEMP /" F, 15, 34556);</p> <p>System.console.readline (); // string UploadFile = "e: //test_local.rar"; // string str = x.uploadFileEx ("http://localhost/phpmyadmin/uploadAction.php", "post", UploadFile, "File1"); // system.console.writeline (STR); // system.console.readline ();</p> <p>String BS = ""; // Used to record the last bit number BOOL B = false; private int = 0; private static object _synclockObject = new object (); string _f; string _f; private void x_datareceive (microshaoft.utils .Httpwebclient sender, microshaoft.utils.downloadloadEventArgs e) {if (! This.b) {lock (_SynclockObject) {if (! This.b) {system.console.write (system.datetime.now.tostring () " The data has been received: "); //system.console.write (system.datetime.now.write () " has received data: "); this.b = true;}}} String f = E.DownloadState.FileName ; If (e.DownloadState.attachmentName! = Null) f = system.io.path.getdirectoryName (f) @ "/" E.DownloadState.attachmentName;</p> <p>THIS._F = F;</p> <p>Using (System.IO.FileStream SW = New System.io.FileStream (f, system.io.filemode.openorcreate, system.io.filecess.readwrite, system.io.fileshare.readwrite) {sw.position = e. DownloadState.position; sw.write (E.DownloadState.Data, 0, E.DownloadState.Data.Length); sw.close ();} string s = system.datetime.now.tostring (); lock.tostring (); lock.tockObject THIS.I = E.DownloadState.Data.Length; System.Console.write (BS "/ B / B / B / B / B / B / B / B / B / B / B" i "/" Sender.fileLength "byte data" s); //system.console.write (BS i "byte data" s); this.bs = new string ('/ b', DIGITS (i) 3 Digits (Sender.FileLength) S.Length);}}</p> <p>INT DIGITS (INT N) // Number of places {n = system.math.abs (n = n / 10; int i = 1; while (n> 0) {n = N / 10; i } Return i;}</p> <p>private void x_ExceptionOccurrs (Microshaoft.Utils.HttpWebClient Sender, Microshaoft.Utils.ExceptionEventArgs e) {System.Console.WriteLine (e.Exception.Message); corresponds to an abnormal re-download HTTP // happens, you can choose their own treatment Microshaoft.Utils.HttpWebClient x = new Microshaoft.Utils.HttpWebClient (); x.DownloadFileChunk (this._F, this._f, e.DownloadState.Position, e.DownloadState.Length); e.ExceptionAction = Microshaoft.Utils .ExceptionActions.Ignore;} private void x_ThreadProcessEnd (Microshaoft.Utils.HttpWebClient Sender, Microshaoft.Utils.ThreadProcessEventArgs e) {// if (e.thread.ThreadState == System.Threading.ThreadState.Stopped) if (this._k == this._k - 1) System.console.writeline ("/ NEND");}}</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-50064.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="50064" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.043</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'M_2F8fXjMqd0KXyaTrLBVHchQiQ0iCHxE2BF03ANvIE6mplzvLc28mhL0eUAfwx9VAxX1202NAJ2KgmN6V6wOCDQ_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>