Nate Pet
Nate Pet

Reputation: 46222

c# DirectoryInfo,GetFiles

I have the following code which works fine. What I am trying to do (in one shot) is to check if a directory exists, and, if so I would like to check if a file exists within the folder. It returns Y if it does or else it returns N:

string s = new DirectoryInfo("C:\\EXP_Reports\\36000").Exists
   ? new DirectoryInfo("C:\\EXP_Reports\\36000").GetFiles("EXP Report #36001.pdf")
       .Any() ? "Y" : "N"
   : "N";

I am wondering if the above code can be optimized further. Please note that I would like to do it in one statement.

Upvotes: 1

Views: 304

Answers (3)

Richard Schneider
Richard Schneider

Reputation: 35477

Why not simply use File.Exists.

bool q = File.Exists(@"C:\EXP_Reports\36000\EXP Report #36001.pdf");

See http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx

I've also changed the code to use a bool instead of a string containing Y or N.

Also, using a verbatim string literal @"..." reads better.

Upvotes: 7

Echilon
Echilon

Reputation: 10244

Couldn't you use string s = File.Exists("C:\\EXP_Reports\\36000\\EXP Report #36001.pdf") ? "Y" : "N";?

Upvotes: 0

Igor
Igor

Reputation: 15893

Use

System.IO.Directory.Exists("...");

and

System.IO.File.Exists("...");

No need to instantiate anything.

If you only need to check file existence, you do not need to check if the directory exists.

Upvotes: 2

Related Questions