HttpWebRequest下载文件和进度条

时间:2013-05-07 08:03:41

标签: c# http httpwebrequest progress

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

感谢。

P.S。这是代码......

    private static Task<HttpResponse> MakeAsyncRequest(string requestString)
    {
        var request = (HttpWebRequest)WebRequest.Create(requestString);
        Task<WebResponse> 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;
        }
    }

1 个答案:

答案 0 :(得分:0)

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

    public static void CopyToStreamAsync(this Stream source, Stream destination,
        Action<Stream, Stream, Exception> completed, Action<uint> progress,
        uint bufferSize, uint? maximumDownloadSize, TimeSpan? timeout)
    {
        byte[] buffer = new byte[bufferSize];

        Action<Exception> 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<IAsyncResult, bool> 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);
    }