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
要檢查的檔案。
傳回
如果呼叫端具有必要的權限,而且 true
包含現有檔案的名稱,則為 path
,否則為 false
。 如果 false
是 path
、無效路徑或長度為零的字串,這個方法也會傳回 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
傳回如果發生任何錯誤。 這可能會在引發例外狀況的情況下發生,例如傳遞無效字元或太多字元的檔名、失敗或遺失的磁碟,或呼叫端沒有讀取檔案的許可權。
適用於
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應