Reputation: 11304
I have 3 different directories where files are available for further processing.
try/catch
.Here is below code, question, what could be the best way to get file path as above functionality?
private static string GetRealPath()
{
const string filePath1 = @"C:\temp1\";
const string filePath2 = @"C:\temp2\";
const string filePath3 = @"C:\temp\";
//looks for file in @"C:\temp1\
try
{
if (Directory.EnumerateFileSystemEntries(filePath1, "*.txt").ToList().Count > 0)
{
return filePath1;
}
}
catch (Exception e) { Console.WriteLine(e); }
//looks for file in @"C:\temp2\
try
{
if (Directory.EnumerateFileSystemEntries(filePath2, "*.txt").ToList().Count > 0)
{
return filePath2;
}
}
catch (Exception e) { Console.WriteLine(e); }
//looks for file in @"C:\temp\
try
{
if (Directory.EnumerateFileSystemEntries(filePath3, "*.txt").ToList().Count > 0)
{
return filePath3;
}
}
catch (Exception e) { Console.WriteLine(e); }
return string.Empty;
}
Upvotes: 0
Views: 91
Reputation: 460018
You could use Directory.Exists
instead:
public static string GetFirstValidPath()
{
string[] paths = { @"C:\temp1\", @"C:\temp2\", @"C:\temp\"};
return paths.FirstOrDefault(p=> Directory.Exists(p)
&& Directory.EnumerateFileSystemEntries(p, "*.txt").Any()) ?? string.Empty;
}
Upvotes: 4