且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查文件是否使用C#和WebClient类的服务器上存在

更新时间:2023-11-26 20:26:58

Web客户端是相当有限的;如果切换到使用的WebRequest ,然后你获得发送一个HTTP HEAD请求的能力。当你发出请求,你要么得到一个错误(如果文件丢失),或 WebResponse类使用有效的 CONTENTLENGTH $ C 。$ C>属性

WebClient is fairly limited; if you switch to using WebRequest, then you gain the ability to send an HTTP HEAD request. When you issue the request, you should either get an error (if the file is missing), or a WebResponse with a valid ContentLength property.

修改示例代码:

WebRequest request = WebRequest.Create(new Uri("http://www.example.com/"));
request.Method = "HEAD";

using(WebResponse response = request.GetResponse()) {
   Console.WriteLine("{0} {1}", response.ContentLength, response.ContentType);
}