एक संभावित पूर्ण फ़ाइल पथ को देखते हुए, मैं उदाहरण के साथ सी: \ dir \ otherDir \ possiblefile मैं ढूंढने के लिए एक अच्छा दृष्टिकोण जानना चाहता हूं पता लगाएँ कि क्याजांचें कि फ़ाइल या पैरेंट निर्देशिका मौजूद है, एक संभावित पूर्ण फ़ाइल पथ
C: \ dir \ otherDir \ possiblefile फ़ाइल
या C: \ dir \ otherDir निर्देशिका
मौजूद है। मैं फ़ोल्डर बनाना नहीं चाहता, लेकिन अगर यह मौजूद नहीं है तो मैं फ़ाइल बनाना चाहता हूं। फ़ाइल में कोई एक्सटेंशन हो सकता है या नहीं। मैं कुछ इस तरह पूरा करने के लिए करना चाहते हैं:
मैं एक समाधान के साथ आया था, लेकिन यह मेरी राय में एक छोटा सा overkill है। ऐसा करने का एक आसान तरीका होना चाहिए।
// Let's example with C:\dir\otherDir\possiblefile
private bool CheckFile(string filename)
{
// 1) check if file exists
if (File.Exists(filename))
{
// C:\dir\otherDir\possiblefile -> ok
return true;
}
// 2) since the file may not have an extension, check for a directory
if (Directory.Exists(filename))
{
// possiblefile is a directory, not a file!
//throw new Exception("A file was expected but a directory was found");
return false;
}
// 3) Go "up" in file tree
// C:\dir\otherDir
int separatorIndex = filename.LastIndexOf(Path.DirectorySeparatorChar);
filename = filename.Substring(0, separatorIndex);
// 4) Check if parent directory exists
if (Directory.Exists(filename))
{
// C:\dir\otherDir\ exists -> ok
return true;
}
// C:\dir\otherDir not found
//throw new Exception("Neither file not directory were found");
return false;
}
कोई सुझाव:
यहाँ मेरी कोड है?
ऐ, इसके अलावा, यह जाना बहुत अच्छा है। –
अब, यह निश्चित रूप से छोटा है, मैन्युअल पार्सिंग से मुझे बचाता है और वैकल्पिक विभाजक हैंडल करता है। वास्तव में मैं क्या देख रहा था! – Joel