32

我想检查一个大文件的 URL 是否存在。我正在使用下面的代码,但它太慢了:

public static bool TryGet(string url)
{
    try
    {
        GetHttpResponseHeaders(url);
        return true;
    }
    catch (WebException)
    {
    }

    return false;
}

public static Dictionary<string, string> GetHttpResponseHeaders(string url)
{
    Dictionary<string, string> headers = new Dictionary<string, string>();
    WebRequest webRequest = HttpWebRequest.Create(url);
    using (WebResponse webResponse = webRequest.GetResponse())
    {
        foreach (string header in webResponse.Headers)
        {
            headers.Add(header, webResponse.Headers[header]);
        }
    }

    return headers;
}
4

1 回答 1

52

你需要设置:

webRequest.Method = "HEAD";

这样,服务器将仅响应标头信息(无内容)。这对于检查服务器是否接受某些操作(即压缩数据等)也很有用。

于 2011-06-04T15:53:43.850 回答