Redigera

Dela via


File.Exists(String) Method

Definition

Determines whether the specified file exists.

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

Parameters

path
String

The file to check.

Returns

true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. This method also returns false if path is null, an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path.

Examples

The following example determines if a file exists.

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."))

Remarks

Don't use the Exists method for path validation; this method merely checks if the file specified in path exists. Passing an invalid path to Exists returns false. To check whether the path contains any invalid characters, you can call the GetInvalidPathChars method to retrieve the characters that are invalid for the file system. You can also create a regular expression to test the whether the path is valid for your environment. For examples of acceptable paths, see File.

To check if a directory exists, see Directory.Exists.

Be aware that another process can potentially do something with the file in between the time you call the Exists method and perform another operation on the file, such as Delete.

The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.

If path describes a directory, this method returns false. Trailing spaces are removed from the path parameter before determining if the file exists.

The Exists method returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.

Applies to

See also