我的 DownloadFile 方法在被长时间调用时抛出 WebException

问题描述

我的 DownloadFile 方法遇到了一个问题,该方法在运行时在我的代码中被循环调用很多次,下载文件有时甚至需要十分之一小时。很长一段时间后(大约运行时间超过 5 小时后),在我的用户的日志中,我可以看到,此方法正在抛出 System.Net.WebException: The operation has timed out。我想知道如何解决这个问题。

public static void DownloadFile(string from,string to)
        {
            try
            {
                HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                HttpWebRequest.DefaultCachePolicy = policy;

                HttpWebRequest httpRequest = (HttpWebRequest)
                WebRequest.Create(from);
                httpRequest.Method = WebRequestMethods.Http.Get;

                HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                httpRequest.CachePolicy = noCachePolicy;
                httpRequest.Headers.Add("Cache-Control","no-cache");

                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                Stream httpResponseStream = httpResponse.GetResponseStream();

                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int bytesRead = 0;

                // Read from response and write to file
                FileStream fileStream = File.Create(to);
                while ((bytesRead = httpResponseStream.Read(buffer,bufferSize)) != 0)
                {
                    fileStream.Write(buffer,bytesRead);
                }

                fileStream.Close();
                httpResponseStream.Close();
                httpResponse.Close();
            }
            catch (Exception e)
            {
                Trace.WriteLine("[DownloadFile] Task Failed :: Exception [" + e.ToString() + "] thrown.");
            }
        }
    ```

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)