验证文件是否存在于网站上

本文关键字:网站 于网站 文件 是否 存在 验证 | 更新日期: 2023-09-27 18:09:02

我正在尝试做一个简单的函数来验证一个特定的文件是否存在于一个网站上。

web请求被设置为头,所以我可以获得文件长度,而不是下载整个文件,但我得到"无法连接到远程服务器"异常。如何验证网站上是否存在文件?

    WebRequest w;
    WebResponse r;
    w = WebRequest.Create("http://website.com/stuff/images/9-18-2011-3-42-16-PM.gif");
    w.Method = "HEAD";
    r = w.GetResponse();

编辑:我的错,原来我的防火墙阻止http请求后,我检查了日志。它没有提示我异常规则,所以我认为这是一个bug。

验证文件是否存在于网站上

我已经测试过了,效果很好:

private bool testRequest(string urlToCheck)
{
    var wreq = (HttpWebRequest)WebRequest.Create(urlToCheck);
    //wreq.KeepAlive = true;
    wreq.Method = "HEAD";
    HttpWebResponse wresp = null;
    try
    {
        wresp = (HttpWebResponse)wreq.GetResponse();
        return (wresp.StatusCode == HttpStatusCode.OK);
    }
    catch (Exception exc)
    {
        System.Diagnostics.Debug.WriteLine(String.Format("url: {0} not found", urlToCheck));
        return false;
    }
    finally
    {
        if (wresp != null)
        {
            wresp.Close();
        }
    }
}

试试这个url: http://www.centrosardegna.com/images/losa/losaabbasanta.png,然后修改图像名称,它将返回false。: -)

try
{
    WebRequest request = HttpWebRequest.Create("http://www.microsoft.com/NonExistantFile.aspx");
    request.Method = "HEAD"; // Just get the document headers, not the data.
    request.Credentials = System.Net.CredentialCache.DefaultCredentials;
    // This may throw a WebException:
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            // If no exception was thrown until now, the file exists and we 
            // are allowed to read it. 
            MessageBox.Show("The file exists!");
        }
        else
        {
            // Some other HTTP response - probably not good.
            // Check its StatusCode and handle it.
        }
    }
}
catch (WebException ex)
{
    // Cast the WebResponse so we can check the StatusCode property
    HttpWebResponse webResponse = (HttpWebResponse)ex.Response;
    // Determine the cause of the exception, was it 404?
    if (webResponse.StatusCode == HttpStatusCode.NotFound)
    {
        MessageBox.Show("The file does not exist!");
    }
    else
    {
        // Handle differently...
        MessageBox.Show(ex.Message);
    }
}