locked
HttpWebRequest如何判断一个链接是下载链接 RRS feed

  • 问题

  • 我查看的资料是查看content-type,但是有那么多种类型,需要怎么判断才能知道是下载文件的呢?
    2014年7月12日 8:24

答案

  • 你好,

    可以使用WebRequest的HEAD方法来判断,

                WebRequest request = WebRequest.Create(new Uri("http://download.microsoft.com/download/B/A/4/BA4A7E71-2906-4B2D-A0E1-80CF16844F5F/dotNetFx45_Full_setup.exe"));
                request.Method = "HEAD";
    
                using (WebResponse response = request.GetResponse())
                {
                    Console.WriteLine("{0} {1}", response.ContentLength, response.ContentType);
                }
                Console.ReadKey();

    如果URI是一个可以下载的地址,则程序运行正常,并且能够输出ContentLength。如果不是一个下载地址,则抛出异常。

    具体方式请参考:

    How to check if a file exists on a server using c# and the WebClient class

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

    谢谢!


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2014年7月14日 2:50