Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# check that a file destination is valid

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.

like image 933
TK. Avatar asked Feb 12 '09 12:02

TK.


4 Answers

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
like image 107
cgreeno Avatar answered Sep 20 '22 00:09

cgreeno


if(System.IO.File.Exists(fileOrDirectoryPath))
{
    //do stuff
}

This should do the trick!

like image 40
xan Avatar answered Sep 22 '22 00:09

xan


If it can't be a new directory, you can just check if it exists.

It looks like you could also use Path.GetInvalidPathChars to check for invalid characters.

like image 45
Instance Hunter Avatar answered Sep 21 '22 00:09

Instance Hunter


You might also want to consider that a valid path in itself is not 100% valid. If the user provides C:\windows\System32, or to a CD drive the operating system could throw an exception when attempting to write.

like image 28
Rad Avatar answered Sep 19 '22 00:09

Rad