Reputation: 46222
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
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
Reputation: 10244
Couldn't you use string s = File.Exists("C:\\EXP_Reports\\36000\\EXP Report #36001.pdf") ? "Y" : "N";
?
Upvotes: 0
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