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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/830435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:21:35  来源:igfitidea点击:

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

c#httpfilewebclientexists

提问by Mats

In my application I use the WebClientclass to download files from a Webserver by simply calling the DownloadFilemethod. 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:

在我的应用程序中,我使用WebClient类通过简单地调用DownloadFile方法从Web服务器下载文件。现在我需要在下载某个文件之前检查它是否存在(或者如果我只想确保它存在)。我有两个问题:

  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?
  1. 在不通过网络传输大量数据的情况下检查文件是否存在于服务器上的最佳方法是什么?(我需要检查的文件数量相当多)
  2. 有没有办法在不下载的情况下获取给定远程文件的大小?

Thanks in advance!

提前致谢!

采纳答案by Tim Robinson

WebClientis 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 WebResponsewith a valid ContentLengthproperty.

WebClient相当有限;如果您切换到 using WebRequest,那么您将能够发送 HTTP HEAD 请求。当您发出请求时,您应该得到一个错误(如果文件丢失)或WebResponse具有有效ContentLength属性的 。

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

回答by Code

When you request file using the WebClientClass, the 404 Error (File Not Found) will lead to an exception. Best way is to handle that exception and use a flag which can be set to see if the file exists or not.

当您使用WebClient类请求文件时,404 错误(找不到文件)将导致异常。最好的方法是处理该异常并使用可以设置的标志来查看文件是否存在。

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. Hope it helps!

您可以将代码放在相应的 if 块中。希望能帮助到你!