檢查 C# 中的檔案是否存在
在 C# 中使用 File.exists 方法檢查檔案在 C# 中是否存在。
首先,檢查檔案是否存在於當前目錄中。
if (File.Exists("MyFile.txt")) {
Console.WriteLine("The file exists.");
}然後檢查檔案是否存在於目錄中。
if (File.Exists(@"D:\myfile.txt")) {
Console.WriteLine("The file exists.");
}我們來看看一個完整的示例,檢查檔案是否存在於 C# 中。
示例
using System;
using System.IO;
class Demo {
static void Main() {
if (File.Exists("MyFile.txt")) {
Console.WriteLine("File exists...");
} else {
Console.WriteLine("File does not exist in the current directory!");
}
if (File.Exists(@"D:\myfile.txt")) {
Console.WriteLine("File exists...");
} else {
Console.WriteLine("File does not exist in the D directory!");
}
}
}輸出
File does not exist in the current directory! File does not exist in the D directory!
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP