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 。 這種情況可能發生在產生例外的情況,例如傳入無效字元或過多字元的檔名、磁碟故障或遺失,或呼叫者無權讀取該檔案。