Public classwebdownload:webclient {Private int_timeout; /// <summary> ///time-out (milliseconds)/// </summary> Public intTimeout {Get { return_timeout; } Set{_timeout=value; } } Publicwebdownload () { This. _timeout =60000; } PublicWebdownload (intTimeout) { This. _timeout =timeout; } protected OverrideWebRequest GetWebRequest (Uri address) {varresult =Base. GetWebRequest (address); Result. Timeout= This. _timeout; returnresult; } Public stringGet (stringURL) { stringHTML =""; vardata = This. Downloaddata (URL); varR_utf8 =NewSystem.IO.StreamReader (NewSystem.IO.MemoryStream (data), Encoding.UTF8);//Place HTML in UTF8 encoded StreamReader varR_GBK =NewSystem.IO.StreamReader (NewSystem.IO.MemoryStream (data), encoding.default);//Place HTML in GBK encoded StreamReader varT_utf8 = R_utf8. ReadToEnd ();//read the HTML content varT_GBK = R_GBK. ReadToEnd ();//read the HTML content if(!isluan (T_utf8))//determine if UTF8 is garbled{html=T_utf8; } Else{html=T_GBK; } returnhtml; } BOOLIsluan (stringtxt) { varbytes =Encoding.UTF8.GetBytes (TXT); //239 191 189 for(vari =0; I < bytes. Length; i++) { if(I < bytes. Length-3) if(Bytes[i] = =239&& Bytes[i +1] ==191&& Bytes[i +2] ==189) { return true; } } return false; } }
Bill: C # WebClient automatically determine whether the encoding is UTF-8 or GBK, and has a time-out judgment function