Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ตรวจสอบว่าไฟล์มีอยู่จริงใน C#

ใช้เมธอด File.Exists ใน C# ตรวจสอบว่าไฟล์มีอยู่หรือไม่

ขั้นแรก ตรวจสอบใน current directory:

if (File.Exists("MyFile.txt")) { Console.WriteLine("The file exists."); }

ตรวจสอบในไดเรกทอรีเฉพาะ:

if (File.Exists(@"D:\myfile.txt")) { Console.WriteLine("The file exists."); }

ตัวอย่าง

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!