Excel列名校验循环提前终止及循环续行技术咨询
Fixing Loop Termination Issues in Excel Column Validation
Hey there! Let's break down your two problems and fix them step by step:
Problem 2: Stopping Column Validation After First Invalid Column
The core issue here is that your code immediately returns true as soon as it finds an invalid column. This exits the method right away, so the loop never gets to check the rest of the columns. Here's how to modify it to validate all columns and collect all errors:
Modified InvalidColumnNames() Method
public Boolean InvalidColumnNames() { bool hasInvalidColumns = false; // Track if any invalid columns are found using (ReadAndStreamFile()) { reader.Read(); int counter = 0; var columnNames = Enumerable.Range(0, reader.FieldCount) .Select(i => reader.GetValue(i)) .ToList(); if (columnNames.Count != 0 && reader.Read()) { for (int columnNumber = 0; columnNumber < columnNames.Count; columnNumber++) { var excel = new ExcelDataReaderFile(); var cellAddress = excel.GetAddress(counter, 0); counter += 1; if (columnNames[columnNumber] != null && columnNames[columnNumber].ToString().Length > columnNameSizeLimit) { Console.WriteLine($"[{GetFileName(file)}]{reader.Name}!{cellAddress} is {columnNames[columnNumber].ToString().Length} characters long and exceeds {columnNameSizeLimit} character column name limit. Supply a valid column name."); hasInvalidColumns = true; // Mark as invalid but keep looping } else if (columnNames[columnNumber] == null) { Console.WriteLine($"[{GetFileName(file)}]{reader.Name}!{cellAddress} is empty. Supply a valid column name."); hasInvalidColumns = true; // Mark as invalid but keep looping } // No return here - loop continues to next column } } else { Console.WriteLine($"[{GetFileName(file)}]{reader.Name} is empty and cannot be validated. Supply a non-empty file."); hasInvalidColumns = true; } } reader.Dispose(); reader.Close(); return hasInvalidColumns; // Return true only if any invalid columns were found }
Key Changes:
- Added a
hasInvalidColumnsflag to track if any errors were found, instead of returning immediately. - Removed the early
return truestatements when invalid columns are detected—now we just set the flag and let the loop continue. - Fixed a typo:
Conseol.WriteLine→Console.WriteLine. - Corrected the character length check in the first error message (you had
columnNumber.ToString().Lengthinstead of the actual column name's length).
Problem 1: Letting a Loop Continue When a Condition is True
This ties directly into the fix above! If your loop stops when a condition is true, it's almost always because you're using return (which exits the entire method) or break (which exits the loop). To keep the loop running:
- Avoid using
returnorbreakwhen you just want to handle the current item and move on. - Use
continueonly if you need to skip the rest of the current iteration and jump to the next one (not necessary here since we want to process all columns). - Use a flag variable (like
hasInvalidColumns) to track state instead of exiting early.
Bonus: Main Program Cleanup
Your main program has a small syntax issue (an extra else at the end). Here's the corrected version:
class Program { public static void Main(string[] args) { string path = ConfigurationManager.AppSettings["path"].ToString(); string search = ConfigurationManager.AppSettings["search"].ToString(); ExcelDataReaderFile excelDataReaderFile = new ExcelDataReaderFile(); string[] fileEntries = Directory.GetFiles(path, "*" + search + "*", SearchOption.AllDirectories); int counter = 0; // Use int instead of dynamic for type safety BasicValidation basicValidation = new BasicValidation(); // Reuse instance instead of creating inside loop foreach (string file in fileEntries) { basicValidation = new BasicValidation(file, 128, 32767, 128, 128); counter += 1; Logger.Info($"Validating {basicValidation.GetFileName(file)}"); if (basicValidation.InvalidColumnNames()) { Console.WriteLine($"{counter}) {basicValidation.GetFileName(file)} in {path} has failed validation. Check the error log for details."); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } else { Console.WriteLine($"{counter}) {basicValidation.GetFileName(file)} in {file} has passed validation checks."); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } // Removed the extra else here Console.WriteLine("All files validated! Press any key to exit..."); Console.ReadKey(); } }
内容的提问来源于stack exchange,提问作者Kira
相关产品推荐
相关产品推荐

