C# check that a file destination is valid

2019-04-05 08:10发布

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.

5条回答
2楼-- · 2019-04-05 08:41

The previous answer is correct with respect to checking whether a given file or directory exists. The Path class also contains a number of functions that are useful for validating or manipulating the various components of a path.

查看更多
霸刀☆藐视天下
3楼-- · 2019-04-05 08:46

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.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-04-05 08:47

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.

查看更多
不美不萌又怎样
5楼-- · 2019-04-05 08:57
if(System.IO.File.Exists(fileOrDirectoryPath))
{
    //do stuff
}

This should do the trick!

查看更多
乱世女痞
6楼-- · 2019-04-05 09:01

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
查看更多
登录 后发表回答