File.Exists(String) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
确定指定的文件是否存在。
public:
static bool Exists(System::String ^ path);
public static bool Exists(string path);
public static bool Exists(string? path);
static member Exists : string -> bool
Public Shared Function Exists (path As String) As Boolean
参数
- path
- String
要检查的文件。
返回
如果调用方具有所需的权限并且 path 包含现有文件的名称,则 true;否则,false。 如果 pathnull、路径无效或长度为零的字符串,此方法也会返回 false。 如果调用方没有足够的权限读取指定文件,则不会引发异常,并且该方法将返回 false,而不考虑存在 path。
示例
以下示例确定文件是否存在。
string curFile = @"c:\temp\test.txt";
Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");
let curFile = @"c:\temp\test.txt"
printfn
$"""{if File.Exists curFile then
"File exists."
else
"File does not exist."}"""
Dim curFile As String = "c:\temp\test.txt"
Console.WriteLine(If(File.Exists(curFile), "File exists.", "File does not exist."))
注解
不要使用 Exists 方法进行路径验证;此方法仅检查 path 中指定的文件是否存在。 将无效路径传递给 Exists 将返回 false。 若要检查路径是否包含任何无效字符,可以调用 GetInvalidPathChars 方法来检索文件系统无效的字符。 还可以创建正则表达式来测试路径是否对环境有效。 有关可接受路径的示例,请参阅 File。
若要检查目录是否存在,请参阅 Directory.Exists。
请注意,在调用 Exists 方法并对该文件执行另一个操作(如 Delete)之间,另一个进程可能会对文件执行某些操作。
允许 path 参数指定相对路径或绝对路径信息。 相对路径信息解释为相对于当前工作目录。 若要获取当前工作目录,请参阅 GetCurrentDirectory。
如果 path 描述目录,此方法将返回 false。 在确定文件是否存在之前,将从 path 参数中删除尾随空格。
Exists 方法在尝试确定指定文件是否存在时发生任何错误,则返回 false。 在引发异常的情况下,可能会引发异常,例如传递无效字符或字符过多、磁盘失败或缺失的文件名,或者调用方没有读取文件的权限。