ใช้วิธี File.exists ใน C# เพื่อตรวจสอบว่าไฟล์ออกจาก 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!