C# check that a file destination is valid

不羁的心 提交于 2019-12-04 03:00:27

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
if(System.IO.File.Exists(fileOrDirectoryPath))
{
    //do stuff
}

This should do the trick!

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.

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!