如果键入了错误的文件名但是似乎无法使用try catch块保留所有内容,我想在此类中处理FileNotFoundException。请指点
此处抛出异常(FileStream fileStream = File.OpenRead(fileName))
public class XcelReader
{
private readonly List<List<IRule>> m_Rules;
public XcelReader(List<List<IRule>> rules)
{
m_Rules = rules;
}
public void ValidateWorksheet(string fileName)
{
bool allRulesPassed = true;
WorkbookProvider workbookProvider = new WorkbookProvider();
int counter = 0;
IWorkbook workbook;
using (FileStream fileStream = File.OpenRead(fileName))
workbook = workbookProvider.GetWorkbook(fileStream, SpreadsheetType.Xlsx);
for (int rowCounter = 1; rowCounter < workbook.Worksheets[1].Rows.Count; rowCounter++)
{
IRow row = workbook.Worksheets[1].Rows[rowCounter];
for (int columnCounter = +1; columnCounter < row.Cells.Count; columnCounter++)
{
List<string> failedRules = ColumnValueIsValid(row.Cells[columnCounter].Value, m_Rules[columnCounter]);
failedRules.ForEach(failedRule =>
{
allRulesPassed = false;
Console.WriteLine("\n[{0}:{1}] Failed: {2}", rowCounter +1, GetColumnHeaderValue(columnCounter + 1), failedRule);
counter++;
if (counter > 20)
{
Console.WriteLine("\nHit enter to page down................");
Console.ReadLine();
counter = 0;
}
});
}
}
if(allRulesPassed)
Console.WriteLine(@"WOOHOO! worksheet is hunky dory Hit enter to continue");
}
private string GetColumnHeaderValue(int columnCounter)
{
return new Base26Converter().FromBase10(columnCounter);
}
private List<string> ColumnValueIsValid(string value, List<IRule> rules)
{
List<string> failedRules = new List<string>();
rules.ForEach(rule =>
{
if(!rule.IsValid(value))
failedRules.Add(rule.GetReasonForFailure(value));
});
return failedRules;
}
}