C# check that a file destination is valid

TK. picture TK. · Feb 12, 2009 · Viewed 16.1k times · Source

Is there a standard function to check that a specified directory is valid?

The reason I ask is that I am receiving an absolute directory string and filename from a user and I want to sanity check the location to check that it is valid.

Answer

cgreeno picture cgreeno · Feb 12, 2009

For a file

File.Exists(string)

For a Directory

Directory.Exists(string)

NOTE: If you are reusing an object you should consider using the FileInfo class vs the static File class. The static methods of the File class does a possible unnecessary security check each time.
FileInfo - DirectoryInfo - File - Directory

 FileInfo fi = new FileInfo(fName);
 if (fi.Exists)
    //Do stuff

OR

DirectoryInfo di = new DirectoryInfo(fName);
 if (di.Exists)
    //Do stuff