I have the following code for downloading a file. When i am downloading a file with a browser then it is downloading like 1mbps but when i am downloading with my code it is downloading like 200kbps or so. Why is the code downloading slowly? Is it something due to writing the file every 4096 bytes?
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);
}