本文介绍了如何检查是否System.Net.WebClient.DownloadData正在下载的二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Web客户端来下载使用WinForms应用程序从网页文件。不过,我真的只是想下载HTML文件。任何其他类型的,我会想要忽略。

I am trying to use WebClient to download a file from web using a WinForms application. However, I really only want to download HTML file. Any other type I will want to ignore.

我查了 WebResponse.ContentType ,但其价值始终是

I checked the WebResponse.ContentType, but its value is always null.

任何人有任何想法可能是什么原因呢?

Anyone have any idea what could be the cause?

推荐答案

鉴于你的更新,您可以通过GetWebRequest改变。方法做到这一点:

Given your update, you can do this by changing the .Method in GetWebRequest:

using System;
using System.Net;
static class Program
{
    static void Main()
    {
        using (MyClient client = new MyClient())
        {
            client.HeadOnly = true;
            string uri = "http://www.google.com";
            byte[] body = client.DownloadData(uri); // note should be 0-length
            string type = client.ResponseHeaders["content-type"];
            client.HeadOnly = false;
            // check 'tis not binary... we'll use text/, but could
            // check for text/html
            if (type.StartsWith(@"text/"))
            {
                string text = client.DownloadString(uri);
                Console.WriteLine(text);
            }
        }
    }

}

class MyClient : WebClient
{
    public bool HeadOnly { get; set; }
    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest req = base.GetWebRequest(address);
        if (HeadOnly && req.Method == "GET")
        {
            req.Method = "HEAD";
        }
        return req;
    }
}

另外,你可以重写GetWebRespons()的时候,也许是抛出一个异常,如果它是不是你想要的检查头:

Alternatively, you can check the header when overriding GetWebRespons(), perhaps throwing an exception if it isn't what you wanted:

protected override WebResponse GetWebResponse(WebRequest request)
{
    WebResponse resp = base.GetWebResponse(request);
    string type = resp.Headers["content-type"];
    // do something with type
    return resp;
}

这篇关于如何检查是否System.Net.WebClient.DownloadData正在下载的二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 06:10