如何检查文件是否使用C#和WebClient类的服务器上存在 [英] How to check if a file exists on a server using c# and the WebClient class
问题描述
在我的应用程序使用 Web客户端类通过简单地调用 DownloadFile 方式从Web服务器下载文件。现在,我需要检查是否下载之前它一定的文件存在(或者在情况下,我只是想确保它的存在)。我有两个问题与:
In my application I use the WebClient class to download files from a Webserver by simply calling the DownloadFile method. Now I need to check whether a certain file exists prior to downloading it (or in case I just want to make sure that it exists). I've got two questions with that:
- 什么是检查是否存在服务器上的文件,无需转流得多数据的最佳方式跨线? (这是我需要检查的文件相当庞大的数字)
- 有没有办法得到一个给定的远程文件的大小,而无需下载?
在此先感谢!
推荐答案
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);
}
这篇关于如何检查文件是否使用C#和WebClient类的服务器上存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!