[英]What could be the best way to get file path
I have 3 different directories where files are available for further processing. 我有3个不同的目录,这些文件可用于进一步处理。
try/catch
. 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;
}
You could use Directory.Exists
instead: 您可以改用
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.