ใช้ File.Exists() ตรวจสอบว่าไฟล์มีอยู่จริงหรือไม่ คืนค่า `bool` ไม่โยน Exception
ตัวอย่างพื้นฐาน
using System;
using System.IO;
public class Demo
{
public static void Main()
{
string path = @"E:\new.txt";
if (File.Exists(path))
{
Console.WriteLine("File exists...");
}
else
{
Console.WriteLine("File does not exist in the E directory!");
}
}
}
ผลลัพธ์
File does not exist in the E directory!
จุดสำคัญของ File.Exists
- ไม่โยน Exception - คืน false ถ้า Path ผิด, Permission Denied, หรือเป็น Directory
- Race Condition - ผลลัพธ์อาจล้าสมัยทันที (TOCTOU - Time of Check to Time of Use)
- Case Insensitive บน Windows (ขึ้นอยู่กับ File System)
- Network Path - อาจช้าเนื่องจาก Network Latency
Pattern ที่ปลอดภัยกว่า: Try-Open แทน Check-Then-Open
// ❌ Bad: Race Condition
if (File.Exists(path))
{
string content = File.ReadAllText(path); // อาจล้มเหลวถ้าถูกลบระหว่างเช็ก
}
// ✅ Good: Try-Open Directly
try
{
string content = File.ReadAllText(path);
}
catch (FileNotFoundException)
{
// Handle Not Found
}
catch (IOException ex)
{
// Handle Other IO Errors
}
ตรวจสอบ Directory
if (Directory.Exists(path))
{
Console.WriteLine("Directory exists");
}
// ตรวจสอบทั้ง File และ Directory
FileSystemInfo info = new FileInfo(path); // หรือ DirectoryInfo
if (info.Exists) { /* ... */ }
FileInfo.Exists Property
var fileInfo = new FileInfo(path);
if (fileInfo.Exists)
{
Console.WriteLine($"Size: {fileInfo.Length} bytes");
Console.WriteLine($"Created: {fileInfo.CreationTime}");
Console.WriteLine($"Modified: {fileInfo.LastWriteTime}");
Console.WriteLine($"ReadOnly: {fileInfo.IsReadOnly}");
}
Advanced: FileSystemWatcher (Real-time Monitoring)
using var watcher = new FileSystemWatcher(@"C:\Watch")
{
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite,
Filter = "*.txt"
};
watcher.Created += (s, e) => Console.WriteLine($"Created: {e.Name}");
watcher.Deleted += (s, e) => Console.WriteLine($"Deleted: {e.Name}");
watcher.Changed += (s, e) => Console.WriteLine($"Changed: {e.Name}");
watcher.EnableRaisingEvents = true;
Console.ReadLine();
Path Handling Best Practices
// Cross-platform Path
string path = Path.Combine(basePath, "subfolder", "file.txt");
// Normalize (Resolve .., ., Symlinks)
string fullPath = Path.GetFullPath(path);
// Long Path Support (Windows > 260 chars)
// Enable in .csproj: true
string longPath = @"\\?\C:\Very\Long\Path\..."; // Windows Extended Length Path