我有一个 C# 控制台应用程序,它从网站下载文件。这是我的方法:
public bool DownloadFile(string fileUri, string filePath)
{
using (var response = _GetResponce(fileUri)) {
if (response.StatusCode != HttpStatusCode.OK) {
return false;
}
using (var responseStrm = response.GetResponseStream()) {
using (var fileStrm = new FileStream(filePath, FileMode.OpenOrCreate)) {
var buffer = new byte[CommonConstants.StreamBufferSize];
int bytesRead = responseStrm.Read(buffer, 0, CommonConstants.StreamBufferSize);
while(bytesRead > 0) {
fileStrm.Write(buffer, 0, bytesRead);
bytesRead = responseStrm.Read(buffer, 0, CommonConstants.StreamBufferSize);
}
}
}
}
private HttpWebResponse _GetResponce(string requestedUri, string method = "GET")
{
var request = (HttpWebRequest)WebRequest.Create(requestedUri);
request.Method = method;
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Headers[HttpRequestHeader.AcceptLanguage] = "ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3";
request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip,deflate";
request.Headers[HttpRequestHeader.AcceptCharset] = "windows-1251,utf-8;q=0.7,*;q=0.7";
return (HttpWebResponse)request.GetResponse();
}
我试图增加缓冲区大小,但无济于事。如果我添加线程,它可以提高下载速度吗?