我有以下代码用于下载文件。当我用浏览器下载文件时,它下载像1mbps,但当我下载我的代码时它下载像200kbps左右。为什么代码下载速度慢?这是因为每4096字节写一次文件吗?
private static void DownloadFile(string URL)
{
int defaultchunksize = 4096;
string downloadFolder = GetValue("DownloadFolder"), fileName = Path.Combine(downloadFolder, Path.GetFileName(URL));
Console.WriteLine("Downloading the file {0} ({1}/{2})", Path.GetFileName(URL), CountOfFilesDownloaded + 1, ListOfFilesDownloaded.Count);
if (!Directory.Exists(downloadFolder))
Directory.CreateDirectory(downloadFolder);
if (File.Exists(fileName))
File.Delete(fileName);
///get cookie
string sTmpCookieString = GetGlobalCookies(psarm.Url.AbsoluteUri);//call InternetGetCookieEx
Stopwatch sw = new Stopwatch();
sw.Start();
HttpWebRequest hwrRequest = (HttpWebRequest)WebRequest.Create(URL);
hwrRequest.CookieContainer = GetUriCookieContainer(new Uri(URL));
hwrRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36";
using (WebResponse response = hwrRequest.GetResponse())
{
using (Stream sDataStream = response.GetResponseStream())
{
using (FileStream fs = File.OpenWrite(fileName))
{
byte[] bytesInStream = new byte[defaultchunksize];
int read;
do
{
read = sDataStream.Read(bytesInStream, 0, defaultchunksize);
if (read > 0)
fs.Write(bytesInStream, 0, read);
}
while (read > 0);
fs.Close();
}
}
}
sw.Stop();
CountOfFilesDownloaded++;
Debug.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\" and time taken to download is: {2}", fileName, URL, sw.Elapsed);
Debug.WriteLine("\nDownloaded file saved in the following file system folder:\n\t" + downloadFolder);
Console.WriteLine("Finished downloading the file: {0}", Path.GetFileName(fileName));
Console.WriteLine("Time took to download: {0}", sw.Elapsed);
}