C#开发网站上下线检测工具时遇错误:无法对string类型应用'!'运算符
修复C#网站检测工具中的"cannot apply operator '!' to operand of type 'string'"错误
问题描述
开发网站上下线检测工具时,运行程序出现错误:cannot apply operator '!' to operand of type 'string',错误出现在if语句中。相关代码如下:
using System; using System.Net; namespace cc { class Program { static void Main(string[] args) { Console.WriteLine("Enter Your Website for further checking: "); string url = Console.ReadLine(); System.Threading.Thread.Sleep(3); Console.WriteLine("Checking..."); System.Threading.Thread.Sleep(3); Console.WriteLine("Found some shit."); System.Threading.Thread.Sleep(3); Console.WriteLine("Printing Request..."); WebClient client = new WebClient(); string checksite = client.DownloadString(url); if (!checksite == HttpStatusCode.OK) { Console.WriteLine("Your Bitch is Down!"); } } } }
错误原因
client.DownloadString(url)返回的是网页内容字符串,你试图将它和HttpStatusCode.OK(枚举类型,本质是数字)做比较,类型完全不匹配。!运算符只能用于布尔值,直接对字符串使用!属于语法错误。- 另外,
WebClient.DownloadString如果请求失败(比如网站宕机、404),会直接抛出异常,根本不会返回错误内容让你判断。
修复方案
改用HttpWebRequest获取响应状态码,同时添加异常处理逻辑,以下是修改后的完整代码:
using System; using System.Net; namespace cc { class Program { static void Main(string[] args) { Console.WriteLine("Enter Your Website for further checking: "); string url = Console.ReadLine(); System.Threading.Thread.Sleep(1000); // 改为1秒延迟,让输出可阅读 Console.WriteLine("Checking..."); System.Threading.Thread.Sleep(1000); Console.WriteLine("Sending request..."); System.Threading.Thread.Sleep(1000); try { // 创建HEAD请求,只获取响应头,无需下载整个网页,更高效 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "HEAD"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { Console.WriteLine($"Website is down! Status code: {response.StatusCode}"); } else { Console.WriteLine("Website is up and running!"); } } } catch (WebException ex) { // 捕获所有网络请求异常,处理不同错误场景 if (ex.Response is HttpWebResponse errorResponse) { Console.WriteLine($"Website error! Status code: {errorResponse.StatusCode}"); } else { Console.WriteLine($"Cannot reach website: {ex.Message}"); } } } } }
关键修改点
- 替换
WebClient.DownloadString为HttpWebRequest的HEAD请求,避免下载无用的网页内容,提升检测效率。 - 添加
try-catch块捕获网络异常,覆盖网站宕机、无法连接、404/500等所有错误场景。 - 正确比较
response.StatusCode(枚举类型)和HttpStatusCode.OK,逻辑清晰且符合语法要求。 - 调整
Thread.Sleep的参数为1000毫秒(1秒),让控制台输出有足够时间展示,便于观察流程。
内容的提问来源于stack exchange,提问作者Xanward
相关产品推荐
相关产品推荐

