HttpWebRequest使用注意(发生阻塞的解决办法)

调用

  DownVideo(@"E:\1\1", @"http://121.37.205.228:8102/pass/2020-06-16/09/888888888888cd0018-13-15-2-20200616093537110-湘AX000F-2-现代-H-66-32-12080-X3090IOUYhgT-1.jpg");

 

 

  static public string DownVideo(string ResourceDir, string url)
        {
            var path = string.Empty;
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream stream = null;
            Stream responseStream = null;
            try
            {
                //var fileName = Path.GetFileName(url);
                var fileName =Guid.NewGuid().ToString()+".jpg";
                path = Path.Combine(ResourceDir, fileName);
                fileName = Path.GetFullPath(path);
                if (!Directory.Exists(Path.GetDirectoryName(fileName)))
                    Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                // 设置参数
                request = WebRequest.Create(url) as HttpWebRequest;
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                responseStream = response.GetResponseStream();
                //创建本地文件写入流
               stream = new FileStream(path, FileMode.Create);
                byte[] bArr = new byte[1024];
                int size = responseStream.Read(bArr, 0, bArr.Length);
                while (size > 0)
                {
                    stream.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, bArr.Length);
                }
                stream.Close();
                responseStream.Close();
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                if (responseStream != null)
                {
                    responseStream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                if (stream != null)
                {
                    stream.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }

            return path;
        }

 

posted on 2020-07-07 09:49  红磨坊后的白桦树  阅读(151)  评论(0编辑  收藏  举报