I would like to find a file with multiple possible names and perform some actions on the file. Could you please advise what would be the best way to do so?
C#
string firstPossiblePath = @"C:\temp\FileVersionOne"
string secondPossiblePath = @"C:\temp\FileVersionTwo"
string secondPossiblePath = @"C:\temp\FileThree"
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....
}
CodePudding user response:
Any time you find yourself writing:
var myVariable1;
var myVariable2;
var myVariable3;
That's candidate for using an array; splitting data out into separate named variables like you have done is probably soon going to become a thorn in your side, because they're hard to work with programmatically. Arrays are easy to work with programmatically.
If you use an array, you can just find the first path that exists and do your actions:
string paths = new[]{
@"C:\temp\FileVersionOne",
@"C:\temp\FileVersionTwo",
@"C:\temp\FileThree"
};
//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;
Remember; any time you have variance between variable names that is just counting, you'll probably soon be changing it to be an array to avoid repeating yourself; consider making it an array from the get-go