HttpWebRequest StreamReader进度百分比

时间:2018-12-14 01:13:36

标签: c# console-application

我正在使用C#控制台应用程序。

我正在使用HttpWebRequestStreamReader解析HTML页面。

如何将Console.Write添加到跟踪进度%的StreamReader

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);

req.UserAgent = "MOZILLA/5.0 (WINDOWS NT 6.1; WOW64) APPLEWEBKIT/537.1 (KHTML, LIKE GECKO) CHROME/21.0.1180.75 SAFARI/537.1";
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

HttpWebResponse response = (HttpWebResponse)req.GetResponse();

string page = string.Empty;

using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
    while (sr.Peek() >= 0)
    {
        page = sr.ReadToEnd();
    }
}

类似于DownloadProgressChanged的{​​{1}}用于下载文件,但不下载网页。

WebClient

1 个答案:

答案 0 :(得分:1)

我从没有做过,但是您可以使用HttpWebResponse.ContentLength属性(这是Content-Length HTTP标头中的值)来获取可以期望的字节总数。然后,您可以一次使用StreamReader.Read()进行一点读取,直到达到ContentLength的大小为止。

类似这样的东西(完全未经测试):

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://");

req.UserAgent = "MOZILLA/5.0 (WINDOWS NT 6.1; WOW64) APPLEWEBKIT/537.1 (KHTML, LIKE GECKO) CHROME/21.0.1180.75 SAFARI/537.1";
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

HttpWebResponse response = (HttpWebResponse)req.GetResponse();

var page = new StringBuilder();

using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
    while (!sr.EndOfStream)
    {
        var buffer = new char[4096];
        var numRead = sr.Read(buffer, 0, buffer.Length);
        html.Append(buffer, 0, numRead);

        var percentage = Convert.ToInt32(Convert.ToDouble(html.Length) / Convert.ToDouble(response.ContentLength) * 100);

        Console.Write("\rProgress: {0}%", percentage);
    }
}
Console.Write("\rProgress: 100%");

现在我知道Content-Length标头是响应中 bytes 的数目,我正在使用StringBuilder.Length来监视进度,即< em> characters 。在Unicode中,单个字符可以等于一个以上的字节,因此以这种方式计算该字符不完全正确,但是足够接近。