我有3个不同的目录,其中的文件可供进一步处理。
try/catch
。以下是代码,问题,以上功能获取文件路径的最佳方法是什么?
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;
}
答案 0 :(得分:4)
您可以改为使用Directory.Exists
:
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;
}