我可以检查文件是否存在,在网址是什么?

问题描述:

我知道我可以在本地,在我的文件系统,检查文件是否存在:

I know I can locally, on my filesystem, check if a file exists:

if(File.Exists(path))

我可以查看在一个特定的远程网址?

Can I check at a particular remote URL?

如果你正在尝试验证Web资源的存在,我会推荐使用的HttpWebRequest 类。这将允许您将 HEAD 发送请求到URL中的问题。只有响应头将被退回,即使资源存在。

If you're attempting to verify the existence of a web resource, I would recommend using the HttpWebRequest class. This will allow you to send a HEAD request to the URL in question. Only the response headers will be returned, even if the resource exists.

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 请求,而不是下载资源(通过不设置方法属性HEAD,或使用 Web客户端类)

Of course, if you want to download the resource if it exists it would most likely be more efficient to send a GET request instead (by not setting the Method property to "HEAD", or by using the WebClient class).