我可以检查URL上是否存在文件?

mrb*_*lah 45 c# file-io

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

if(File.Exists(path))
Run Code Online (Sandbox Code Playgroud)

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

Jus*_*tch 81

如果您正在尝试验证是否存在Web资源,我建议您使用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,如果要下载资源(如果存在),则发送GET请求的效率可能更高(通过不设置Method属性"HEAD"或使用WebClient类).

  • 我建议检查404而不是任何'ol错误代码.例如,如果它是500,则可能是"文件"存在,但服务器在处理请求时遇到(可能是暂时的)错误.要检查404,请确保将`ex.Response`强制转换为`HttpWebResponse`,然后您可以将`StatusCode`与`HttpStatusCode.NotFound`进行比较. (11认同)

cre*_*gox 16

如果你只想复制和粘贴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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我会保持他的观察:

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

  • 不要忘记关闭响应. (3认同)

小智 9

以下是代码的简化版本:

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;
}
Run Code Online (Sandbox Code Playgroud)