File.Exists(String) 方法

定义

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

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

要检查的文件。

返回

如果调用方具有要求的权限并且 true 包含现有文件的名称,则为 path;否则为 false。 如果 falsepath(一个无效路径或零长度字符串),则此方法也将返回 null。 如果调用方不具有读取指定文件所需的足够权限,则不引发异常并且该方法返回 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 文件是否存在。 将无效路径传递给 Existsfalse返回 。 若要检查路径是否包含任何无效字符,可以调用 GetInvalidPathChars 方法来检索对文件系统无效的字符。 还可以创建正则表达式来测试路径是否对环境有效。 有关可接受的路径的示例,请参阅 File

若要检查目录是否存在,请参阅 Directory.Exists

请注意,在调用 Exists 方法并对该文件执行另一个操作(如 Delete)之间,另一个进程可能会对文件执行某些操作。

允许 path 参数指定相对路径信息或绝对路径信息。 相对路径信息被解释为相对于当前工作目录。 若要获取当前工作目录,请参阅 GetCurrentDirectory

如果 path 描述目录,则此方法返回 false。 在确定文件是否存在之前, path 将从 参数中删除尾随空格。

如果在尝试确定指定文件是否存在时发生任何错误,该方法 Exists 将返回 false 。 在引发异常的情况下,可能会发生这种情况,例如传递包含无效字符或字符过多的文件名、磁盘失败或缺失,或者调用方没有读取文件的权限。

适用于

另请参阅