C# में FileNotFoundException पकड़ना
FileNotFoundException तब थ्रो होता है जब फाइल सिस्टम पर निर्दिष्ट पाथ पर फाइल नहीं मिलती। यह IOException से विरासत में मिला है।
उदाहरण: फाइल न मिलने पर एक्सेप्शन
using (StreamReader reader = new StreamReader("nonexistent.txt")) {
string content = reader.ReadToEnd(); // FileNotFoundException यहां थ्रो होगा
}
सही हैंडलिंग: try-catch
using System;
using System.IO;
class Program {
static void Main() {
string path = "new.txt"; // यह फाइल मौजूद नहीं है
try {
using (StreamReader reader = new StreamReader(path)) {
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
catch (FileNotFoundException ex) {
Console.WriteLine("File Not Found!");
Console.WriteLine($"Path: {ex.FileName}");
Console.WriteLine($"Message: {ex.Message}");
}
catch (DirectoryNotFoundException ex) {
Console.WriteLine("Directory not found: " + ex.Message);
}
catch (IOException ex) {
Console.WriteLine("I/O Error: " + ex.Message);
}
}
}
आउटपुट
File Not Found! Path: new.txt Message: Could not find file 'C:\Current\Directory\new.txt'.
बेहतर दृष्टिकोण: पूर्व-जांच (Defensive Check)
if (File.Exists(path)) {
using (var reader = new StreamReader(path)) {
// पढ़ें
}
} else {
Console.WriteLine("File does not exist.");
}
File.Exists vs Try-Catch
| दृष्टिकोण | पक्ष | विपक्ष |
|---|---|---|
File.Exists | सरल, एक्सेप्शन ओवरहेड नहीं | TOCTOU रेस कंडीशन (चेक के बाद फाइल डिलीट हो सकती है) |
try-catch | एटॉमिक, रेस-फ्री | एक्सेप्शन ओवरहेड (लेकिन दुर्लभ के लिए ठीक) |
अन्य सामान्य फाइल एक्सेप्शन्स
DirectoryNotFoundException: डायरेक्टरी पाथ अमान्य।UnauthorizedAccessException: परमिशन नहीं।PathTooLongException: पाथ > 260 कैरेक्टर्स (Windows डिफ़ॉल्ट)।DriveNotFoundException: ड्राइव मौजूद नहीं।
निष्कर्ष
फाइल ऑपरेशन्स में हमेशा try-catch उपयोग करें। FileNotFoundException को विशिष्ट रूप से पकड़ें ताकि यूजर-फ्रेंडली मैसेज दे सकें। using स्टेटमेंट से स्ट्रीम ऑटो-क्लोज़ होती है।