C# 检查文件目标是否有效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/541085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# check that a file destination is valid
提问by TK.
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.
我问的原因是我从用户那里收到一个绝对目录字符串和文件名,我想对位置进行完整性检查以检查它是否有效。
采纳答案by cgreeno
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 类与静态 File 类。File 类的静态方法每次都可能进行不必要的安全检查。
FileInfo- DirectoryInfo-文件-目录
FileInfo fi = new FileInfo(fName);
if (fi.Exists)
//Do stuff
OR
或者
DirectoryInfo di = new DirectoryInfo(fName);
if (di.Exists)
//Do stuff
回答by xan
if(System.IO.File.Exists(fileOrDirectoryPath))
{
//do stuff
}
This should do the trick!
这应该可以解决问题!
回答by Crippledsmurf
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.
关于检查给定文件或目录是否存在,上一个答案是正确的。Path 类还包含许多可用于验证或操作路径的各种组件的函数。
回答by Instance Hunter
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.
看起来您还可以使用 Path.GetInvalidPathChars 来检查无效字符。
回答by Rad
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.
您可能还需要考虑有效路径本身并不是 100% 有效的。如果用户提供 C:\windows\System32 或 CD 驱动器,则操作系统在尝试写入时可能会引发异常。