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

Kiểm tra sự tồn tại của file trong C#

Kiểm tra file E:\new.txt:

if (File.Exists(@"E:\new.txt"))
{
    Console.WriteLine("File tồn tại...");
}

Ví dụ hoàn chỉnh

using System;
using System.IO;

public class Demo
{
    public static void Main()
    {
        if (File.Exists(@"E:\new.txt"))
        {
            Console.WriteLine("File tồn tại...");
        }
        else
        {
            Console.WriteLine("File không tồn tại ở ổ E!");
        }
    }
}

Kết quả

File không tồn tại ở ổ E!

Lưu ý:

  • Dùng @ verbatim string để tránh escape backslash
  • File.Exists trả về false nếu path là directory, không có quyền truy cập, hoặc path quá dài
  • Kiểm tra directory: Directory.Exists(path)