File.Exists(String) 方法

定义

确定指定的文件是否存在。

public:
 static bool Exists(System::String ^ path);
public static bool Exists(string path);
static member Exists : string -> bool
Public Shared Function Exists (path As String) As Boolean

参数

path
String

要检查的文件。

返回

true 如果调用方具有所需的权限并 path 包含现有文件的名称,则为 ;否则为 false。 此方法还返回false无效null路径或零长度字符串。path 如果调用方没有足够的权限读取指定文件,则不会引发异常,并且该方法将返回 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 在尝试确定指定文件是否存在时发生任何错误。 在引发异常的情况下,可能会引发异常,例如传递无效字符或字符过多、磁盘失败或缺失的文件名,或者调用方没有读取文件的权限。

适用于

另请参阅