验证文件存在于网站上

时间:2011-09-18 21:25:11

标签: c# .net webrequest

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

Web请求设置为head,因此我可以获取文件长度而不是下载整个文件,但是我得到“无法连接到远程服务器”异常。 如何验证网站上是否存在文件?

    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请求。 它没有提示我一个例外规则,所以我认为这是一个错误。

2 个答案:

答案 0 :(得分:1)

我已经测试了这个并且工作正常:

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();
        }
    }
}

尝试使用此网址:http://www.centrosardegna.com/images/losa/losaabbasanta.png然后修改图片名称,它将返回false。 ; - )

答案 1 :(得分:0)

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);
    }
}