How to check if System.Net.WebClient.DownloadData is downloading a binary file?

前端 未结 7 718
太阳男子
太阳男子 2020-11-29 00:24

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

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 01:11

    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;
        }
    }
    

    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;
    }
    

提交回复
热议问题