繁体   English   中英

Stream.read()非常慢

[英]Stream.read() is very slow

我有以下用于下载文件的代码。 当我使用浏览器下载文件时,它的下载速度约为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);
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM