如何检查互联网上的文件是否仍然存在?

问题描述:

我想知道是否有一种简单的方法来检测文件是否仍然存在于网络上.我知道它的错误代码是404,但是您将如何检测到它.

我想要的是一种方法,如果我为该方法提供直接的URL链接,则该方法返回false或true(www.somesite/filename.zip).

I was wondering if there is a easy way to detect if a file still exists on the net. I know that the error code for it is 404 but how would you detect it.

What I''d like is to have a method that returns false or true if I give the method a direct url link (www.somesite/filename.zip).

private static bool FileExists(string url)
{
    bool b = true;


    try
    {
        WebClient wc = new WebClient();
        wc.OpenRead(url);
    }
    catch (WebException ex)
    {
        //(ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotFound)
        b = false;
    }
    return b;
}



请注意,这将起作用,但是可能由于多种原因(服务器关闭,访问被拒绝)导致连接失败.



Note that this will work but there might be several reasons (server down, access denied) why a connection may fail.