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.Existstrả 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)