加载列表中的第一个现有文件并执行操作



我想找到一个具有多个可能名称的文件,并对该文件执行一些操作。你能告诉我最好的方法是什么吗?

C#

string firstPossiblePath = @"C:tempFileVersionOne"
string secondPossiblePath = @"C:tempFileVersionTwo"
string secondPossiblePath = @"C:tempFileThree"
if(File.Exists(firstPossiblePath)
{
ReportPath(firstPossiblePath)
PerformAction1(firstPossiblePath)
PerformAction2(firstPossiblePath)
var1.Property = firstPossiblePath
var2.Property = firstPossiblePath
}
else if(File.Exists(secondPossiblePath)
{
ReportPath(secondPossiblePath)
PerformAction1(secondPossiblePath)
PerformAction2(secondPossiblePath)
var1.Property = secondPossiblePath
var2.Property = secondPossiblePath
}
else if(File.Exists(thirdPossiblePath)
{
ReportPath(thirdPossiblePath)
PerformAction1(thirdPossiblePath)
PerformAction2(thirdPossiblePath)
var1.Property = thirdPossiblePath
var2.Property = thirdPossiblePath
}
else
{
throw....
}

任何时候你发现自己在写:

var myVariable1;
var myVariable2;
var myVariable3;

这是使用数组的候选者;像您所做的那样将数据拆分为单独的命名变量可能很快就会成为您的眼中钉,因为它们很难通过编程进行处理。数组很容易通过编程进行处理。


如果你使用一个数组,你可以找到第一个存在的路径并执行你的操作:

string paths = new[]{
@"C:tempFileVersionOne",   
@"C:tempFileVersionTwo", 
@"C:tempFileThree"
};
//this will throw an exception "sequence contains no elements" if none of the files exist
//you can also consider swapping it to FirstOrDefault and checking if path is null, then throw an exception if it is
var path = paths.First(File.Exists);

ReportPath(path);
PerformAction1(path);
PerformAction2(path);
var1.Property = path;
var2.Property = path;

记住;任何时候,只要变量名之间有差异,而且还在计算中,你可能很快就会将其更改为数组,以避免重复;考虑从一开始就把它做成一个阵列

最新更新