Csharp/C#教程:HttpWebRequest下载文件和进度条分享


HttpWebRequest下载文件和进度条

我在网上搜索但是在使用HttpWebRequest下载文件时找不到任何进展方法。 这门课程是否支持进步? 任何链接,教程,提示将不胜感激。

谢谢。

PS这是代码……

private static Task MakeAsyncRequest(string requestString) { var request = (HttpWebRequest)WebRequest.Create(requestString); Task requestTask = Task.Factory.FromAsync( request.BeginGetResponse, asyncResult => request.EndGetResponse(asyncResult), null); return requestTask.ContinueWith(t => ReadStreamFromResponce(t.Result)); } private static HttpResponse ReadStreamFromResponce(WebResponse result) { var responseobject = new HttpResponse(); var response = (HttpWebResponse)result; responseobject.StatusCode = (short)response.StatusCode; if (!IsSuccess(responseobject.StatusCode)) return responseobject; using (var responseStream = response.GetResponseStream()) using (var ms = new MemoryStream()) { responseStream.CopyTo(ms); responseobject.SetResponse(ms.ToArray()); return responseobject; } } 

而不是在Synchronous中复制响应流,尝试复制Asynchronous并在下面的函数中挂钩Delegates,你应该能够获得下载的字节数的进度,将其显示到进度条….

上述就是C#学习教程:HttpWebRequest下载文件和进度条分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)

  public static void CopyToStreamAsync(this Stream source, Stream destination, Action completed, Action progress, uint bufferSize, uint? maximumDownloadSize, TimeSpan? timeout) { byte[] buffer = new byte[bufferSize]; Action done = exception => { if (completed != null) { completed(source, destination, exception); } }; int maxDownloadSize = maximumDownloadSize.HasValue ? (int)maximumDownloadSize.Value : int.MaxValue; int bytesDownloaded = 0; IAsyncResult asyncResult = source.BeginRead(buffer, 0, new[] { maxDownloadSize, buffer.Length }.Min(), null, null); Action endRead = null; endRead = (innerAsyncResult, innerIsTimedOut) => { try { int bytesRead = source.EndRead(innerAsyncResult); if (innerIsTimedOut) { done(new TimeoutException()); } int bytesToWrite = new[] { maxDownloadSize - bytesDownloaded, buffer.Length, bytesRead }.Min(); destination.Write(buffer, 0, bytesToWrite); bytesDownloaded += bytesToWrite; if (!progress.IsNull() && bytesToWrite > 0) { progress((uint)bytesDownloaded); } if (bytesToWrite == bytesRead && bytesToWrite > 0) { asyncResult = source.BeginRead(buffer, 0, new[] { maxDownloadSize, buffer.Length }.Min(), null, null); // ReSharper disable PossibleNullReferenceException // ReSharper disable AccessToModifiedClosure asyncResult.FromAsync((ia, isTimeout) => endRead(ia, isTimeout), timeout); // ReSharper restore AccessToModifiedClosure // ReSharper restore PossibleNullReferenceException } else { done(null); } } catch (Exception exc) { done(exc); } }; asyncResult.FromAsync((ia, isTimeout) => endRead(ia, isTimeout), timeout); } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。

如若转载,请注明出处:https://www.ctvol.com/cdevelopment/985081.html

(0)
编程编程
上一篇 2021年12月21日
下一篇 2021年12月21日

精彩推荐