c# - 检查远程网络服务器上是否存在 .txt 文件

标签 c# httpwebrequest

我正在尝试从网址检查 .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。如何解决这个问题呢。提前致谢。

最佳答案

使用 HttpWebResponse 对象的 StatusCode 属性。

response = (HttpWebResponse)webRequest.GetResponse();

if(response.StatusCode == HttpStatusCode.NotFound)
{
  result = false;
}
else
{
  result = true;
}

查看list of possible status codes查看您想要将哪些文件解释为不存在的文件。

关于c# - 检查远程网络服务器上是否存在 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50139435/

相关文章:

C# Web 请求异常 : The underlying connection was closed: An unexpected error occurred on a receive

c# - Fluent NHibernate - HasMany 复合键

java - 对每个 httpclient 请求重复使用相同的 session

c# - 如何让应用程序名称显示在打开方式列表中?

c# - 具有重新分析点的 FolderBrowserDialog SelectedPath

c# - 通过 SSL 的 HttpWebRequest?

c# - 接收具有不同编码的发布数据

c# - HttpWebRequest 到与域解析到的 IP 不同的 IP

c# - Unity - 根据某些条件解决依赖关系

c# - 识别我的 dotnet 版本