我可以检查一个文件是否存在于一个URL?

我知道我可以在本地文件系统上检查一个文件是否存在:

if(File.Exists(path)) 

我可以检查特定的远程URL吗?

如果您试图validationWeb资源的存在,我会build议使用HttpWebRequest类。 这将允许您发送HEAD请求到有问题的URL。 即使资源存在,也只会返回响应头文件。

 var url = "http://www.domain.com/image.png"; HttpWebResponse response = null; var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "HEAD"; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { /* A WebException will be thrown if the status of the response is not `200 OK` */ } finally { // Don't forget to close your response. if (response != null) { response.Close(); } } 

当然,如果你想下载资源(如果存在的话),最有可能发送一个GET请求(通过不设置Method属性为"HEAD"或使用WebClient类)。

如果你想复制和粘贴Justin的代码,并得到一个方法来使用,下面是我已经实现它:

 using System.Net; public class MyClass { static public bool URLExists (string url) { bool result = false; WebRequest webRequest = WebRequest.Create(url); webRequest.Timeout = 1200; // miliseconds webRequest.Method = "HEAD"; HttpWebResponse response = null; try { response = (HttpWebResponse)webRequest.GetResponse(); result = true; } catch (WebException webException) { Debug.Log(url +" doesn't exist: "+ webException.Message); } finally { if (response != null) { response.Close(); } } return result; } } 

我会保持他的观察:

如果要下载资源,并且它存在,则发送GET请求会更有效,而不是将Method属性设置为"HEAD"或使用WebClient类。

以下是代码的简化版本:

 public bool URLExists(string url) { bool result = true; WebRequest webRequest = WebRequest.Create(url); webRequest.Timeout = 1200; // miliseconds webRequest.Method = "HEAD"; try { webRequest.GetResponse(); } catch { result = false; } return result; } 

如果您使用uncpath或映射驱动器,这将工作正常。

如果您使用的是Web地址(http,ftp等),则最好使用WebClient – 如果WebException不存在,您将得到一个WebException。

 public static bool UrlExists(string file) { bool exists = false; HttpWebResponse response = null; var request = (HttpWebRequest)WebRequest.Create(file); request.Method = "HEAD"; request.Timeout = 5000; // milliseconds request.AllowAutoRedirect = false; try { response = (HttpWebResponse)request.GetResponse(); exists = response.StatusCode == HttpStatusCode.OK; } catch { exists = false; } finally { // close your response. if (response != null) response.Close(); } return exists; } 

我的版本:

  public bool IsUrlExist(string url, int timeOutMs = 1000) { WebRequest webRequest = WebRequest.Create(url); webRequest.Method = "HEAD"; webRequest.Timeout = timeOut; try { var response = webRequest.GetResponse(); /* response is `200 OK` */ response.Close(); } catch { /* Any other response */ return false; } return true; } 

带定义超时的Anoter版本:

 public bool URLExists(string url,int timeout = 5000) { ... webRequest.Timeout = timeout; // miliseconds ... }