我正在尝试从网址检查.txt文件是否存在。这是我的代码:
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)
{
//(url + " doesn't exist: " + webException.Message);
}
finally
{
if (response != null)
{
response.Close();
}
}
return result;
}
如果我输入“http://www.example.com/demo.txt”不是有效的文件路径和网站显示404错误页面,则此代码返回true
。如何解决这个问题呢。提前谢谢。
答案 0 :(得分:2)
使用StatusCode
对象的HttpWebResponse
属性。
response = (HttpWebResponse)webRequest.GetResponse();
if(response.StatusCode == HttpStatusCode.NotFound)
{
result = false;
}
else
{
result = true;
}
查看list of possible status codes,查看哪些文件要解释为文件不存在。