I am trying to build a website up and down checker. but when I try to run my program I get this error: (cannot apply operator '!' to operand of type 'string')
How can I fix it?
I'm new to c# btw.
the error is in the if statement.
this is the code:
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!");
}
}
}
}
CodePudding user response:
First of all, (!string == othervalue)
doesn't mean what you think it does. You're taking the negation of a string, which makes no sense, and then seeing if it's equal to the value on the other side, because !
has higher operator precedence than ==
.
But let's say you fix that: either A != B
or !(A == B)
would work. You still have a problem, because data types matter. It rarely makes sense to check the equality of two different kinds of object.
In this case, DownloadString()
does not return an HttpStatusCode
at all. It returns the body from whatever HttpResponse was provided by the page as a string, and throws an exception for anything that's not a good status code.
So you want this:
try
{
client.DownloadString(url);
}
catch(WebException ex)
{
Console.WriteLine("Your site is Down!");
}
CodePudding user response:
In order to check if a string is not 'something' you have to add ()
like that:
!(checksite == HttpStatusCode.OK)
or
checksite != HttpStatusCode.OK
CodePudding user response:
You have to use the != comparison.
Currently, you try to negate the string itself, which is not possible.
PS: I would change the outputs to something less offensive.