views:

73

answers:

3

I'm getting the error "Operator '||' cannot be applied to operands of type 'bool' and 'string'" when I use the below statement.

if (File.Exists(@"C:\file1.exe") || (@"c:\file2.exe"))
  {
     do something
  }

How can I do this?

Thanks

+11  A: 

You almost had it...

if (File.Exists(@"C:\file1.exe") || File.Exists(@"c:\file2.exe"))
{
   //do something
}

In an if statement, if you want to use || you need to make sure you treat them as separate pieces of a statement.

In this case, the compiler would have no way to "guess" that you are wanting to know if a file exists on your right-hand statement, you need to be explicit with it.

Just like if you want to check to see if a person's age is less than 20 but greater than 18, you would do the following:

if (age < 20 && age > 18) {}

You can't just say age < 20 || 18 because you could be talking about anything, not just age. What if you wanted weight or height as the second check? C# won't be able to guess for you.

Robert Greiner
Doh! Man I can't believe I didn't think of that. Thanks so much!
JimDel
Sure thing. I've made that mistake before as well. Good luck!
Robert Greiner
+2  A: 

try:

(File.Exists(@"C:\file1.exe") || (File.Exists(@"c:\file2.exe"))
Kevin
+3  A: 

Do you mean:

if (File.Exists(@"C:\file1.exe") || File.Exists(@"c:\file2.exe"))
  {
     // do something
  }

File.Exists returns a bool (i.e. true or false), so you have to call it on each path.

kevingessner