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 參數中移除尾端空格。

方法 Existsfalse 傳回嘗試判斷指定的檔案是否存在時發生任何錯誤。 如果引發例外狀況,例如傳遞無效字元或太多字元的檔案名、失敗或遺失的磁片,或呼叫端沒有讀取檔案的許可權,則可能發生此情況。

適用於

另請參閱