Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Kiểm tra File tồn tại trong C#

Dùng File.Exists method kiểm tra file tồn tại.

Kiểm tra file trong current directory:

if (File.Exists("MyFile.txt")) Console.WriteLine("File tồn tại.");

Kiểm tra file trong thư mục cụ thể:

if (File.Exists(@"D:\myfile.txt")) Console.WriteLine("File tồn tại.");

Ví dụ

using System;
using System.IO;
class Demo {
    static void Main() {
        if (File.Exists("MyFile.txt")) Console.WriteLine("File exists...");
        else Console.WriteLine("File KHÔNG tồn tại trong current directory!");
        if (File.Exists(@"D:\myfile.txt")) Console.WriteLine("File exists...");
        else Console.WriteLine("File KHÔNG tồn tại trong D drive!");
    }
}

Kết quả

File KHÔNG tồn tại trong current directory!
File KHÔNG tồn tại trong D drive!