简体   繁体   English

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

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

In my application I use the WebClient class to download files from a Webserver by simply calling the DownloadFile method.在我的应用程序中,我使用WebClient类通过简单地调用DownloadFile方法从Web服务器下载文件。 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:我有两个问题:

  1. What is the best way to check whether a file exists on a server without transfering to much data across the wire?在不通过网络传输大量数据的情况下检查文件是否存在于服务器上的最佳方法是什么? (It's quite a huge number of files I need to check) (我需要检查的文件数量相当多)
  2. Is there a way to get the size of a given remote file without downloading it?有没有办法在不下载的情况下获取给定远程文件的大小?

Thanks in advance!提前致谢!

WebClient is fairly limited; WebClient相当有限; if you switch to using WebRequest , then you gain the ability to send an HTTP HEAD request.如果您切换到使用WebRequest ,则您可以获得发送 HTTP HEAD 请求的能力。 When you issue the request, you should either get an error (if the file is missing), or a WebResponse with a valid ContentLength property.当您发出请求时,您应该得到一个错误(如果文件丢失),或者一个具有有效ContentLength属性的WebResponse

Edit: Example code:编辑:示例代码:

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

When you request file using the WebClient Class, the 404 Error (File Not Found) will lead to an exception.当您使用WebClient类请求文件时,404 错误(找不到文件)将导致异常。 Best way is to handle that exception and use a flag which can be set to see if the file exists or not.最好的方法是处理该异常并使用可以设置的标志来查看文件是否存在。

The example code goes as follows:示例代码如下:

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!!!");
}

You can put your code in respective if blocks.您可以将代码放在相应的 if 块中。 Hope it helps!希望能帮助到你!

What is the best way to check whether a file exists on a server without transfering to much data across the wire?在不通过网络传输大量数据的情况下检查文件是否存在于服务器上的最佳方法是什么?

You can test with WebClient.OpenRead to open the file stream without reading all the file bytes:您可以使用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(); 
}

This will indicate if the file exists at the remote location or not.这将指示该文件是否存在于远程位置。

To fully read the file stream, you would do:要完全读取文件流,您可以执行以下操作:

using (var client = new WebClient()) 
{
    Stream stream = client.OpenRead(url); 
    StreamReader sr = new StreamReader(stream);
    Console.WriteLine(sr.ReadToEnd());
    stream.Close(); 
}

In case anyone stuck with ssl certificate issue如果有人遇到 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM