我可以检查一个文件是否存在于一个 URL 中? [英] can I check if a file exists at a URL?

查看:30
本文介绍了我可以检查一个文件是否存在于一个 URL 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

if(File.Exists(path))

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

Can I check at a particular remote URL?

推荐答案

如果您正在尝试验证 Web 资源是否存在,我建议您使用 HttpWebRequest 类.这将允许您向相关 URL 发送 HEAD 请求.即使资源存在,也只会返回响应头.

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 请求很可能会更有效(通过不设置 Method 属性到 "HEAD",或使用 WebClient 类).

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).

这篇关于我可以检查一个文件是否存在于一个 URL 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆