[英]How to check if a file exists on a server using c# and the WebClient class
在我的应用程序中,我使用WebClient类通过简单地调用DownloadFile方法从Web服务器下载文件。 现在我需要在下载某个文件之前检查它是否存在(或者如果我只想确保它存在)。 我有两个问题:
提前致谢!
WebClient
相当有限; 如果您切换到使用WebRequest
,则您可以获得发送 HTTP HEAD 请求的能力。 当您发出请求时,您应该得到一个错误(如果文件丢失),或者一个具有有效ContentLength
属性的WebResponse
。
编辑:示例代码:
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);
}
当您使用WebClient类请求文件时,404 错误(找不到文件)将导致异常。 最好的方法是处理该异常并使用可以设置的标志来查看文件是否存在。
示例代码如下:
System.Net.HttpWebRequest request = null;
System.Net.HttpWebResponse response = null;
request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("www.example.com/somepath");
request.Timeout = 30000;
try
{
response = (System.Net.HttpWebResponse)request.GetResponse();
flag = 1;
}
catch
{
flag = -1;
}
if (flag==1)
{
Console.WriteLine("File Found!!!");
}
else
{
Console.WriteLine("File Not Found!!!");
}
您可以将代码放在相应的 if 块中。 希望能帮助到你!
在不通过网络传输大量数据的情况下检查文件是否存在于服务器上的最佳方法是什么?
您可以使用WebClient.OpenRead
进行测试以打开文件流,而无需读取所有文件字节:
using (var client = new WebClient())
{
Stream stream = client.OpenRead(url);
// ^ throws System.Net.WebException: 'Could not find file...' if file is not present
stream.Close();
}
这将指示该文件是否存在于远程位置。
要完全读取文件流,您可以执行以下操作:
using (var client = new WebClient())
{
Stream stream = client.OpenRead(url);
StreamReader sr = new StreamReader(stream);
Console.WriteLine(sr.ReadToEnd());
stream.Close();
}
如果有人遇到 ssl 证书问题
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback
(
delegate { return true; }
);
WebRequest request = WebRequest.Create(new Uri("http://.com/flower.zip"));
request.Method = "HEAD";
using (WebResponse response = request.GetResponse())
{
Console.WriteLine("{0} {1}", response.ContentLength, response.ContentType);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.