C# WinForms多文件遍历读取与内容解析问题求助
解决多文件遍历与空格分割内容问题
核心修改思路
把三个文件路径存入集合统一遍历,对每个有效文件逐行读取并按空格分割内容,同时处理空行、多余空格等异常情况,避免重复编写冗余代码。
修改后的完整代码(仅btnVerify_Click方法)
private void btnVerify_Click(object sender, EventArgs e) { // 每次点击时清空文本框 results.Clear(); TextBox errorMessage = results; // 将文件路径存入列表,方便统一遍历 var filePaths = new List<string> { textBox1.Text, textBox2.Text, textBox3.Text }; // 处理三个路径均为空的错误 if (filePaths.All(string.IsNullOrEmpty)) { errorMessage.Text = "ERROR: Cannot have empty path for all three reports!!"; return; } // 统计匹配正确的数量 int matchedCount = 0; // 遍历每个文件路径 foreach (var filePath in filePaths) { // 跳过空路径 if (string.IsNullOrEmpty(filePath)) continue; // 验证文件是否存在 if (!File.Exists(filePath)) { errorMessage.AppendText($"\r\nERROR: File not found - {filePath}"); continue; } // 根据文件名标识文件类型(用于区分不同报告) string fileType = Path.GetFileName(filePath) switch { var name when name.Contains("Assignment") => "Nail Assignment Report", var name when name.Contains("Fixture") => "Nail Fixture Report", var name when name.Contains("Contact") => "Nail Contact List Report", _ => "Unknown Report" }; errorMessage.AppendText($"\r\n{fileType} Found"); try { // 逐行读取文件内容(内存友好,适合大文件) foreach (var line in File.ReadLines(filePath)) { // 跳过空行 if (string.IsNullOrWhiteSpace(line)) continue; // 按空格分割内容,自动移除连续空格产生的空元素 string[] lineParts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // -------------------------- // 这里插入你的业务验证逻辑 // 示例:假设lineParts[0]是接收器引脚,lineParts[1]是报告中的pylon string receiverPin = lineParts[0]; string reportPylon = lineParts[1]; // 调用你的brians函数获取预期pylon string expectedPylon = GetPylonFromReceiverPin(receiverPin); // 比对并统计结果 if (expectedPylon == reportPylon) { matchedCount++; } else { errorMessage.AppendText($"\r\nMismatch: ReceiverPin={receiverPin}, Expected Pylon={expectedPylon}, Report Pylon={reportPylon}"); } // -------------------------- } } catch (Exception ex) { errorMessage.AppendText($"\r\nERROR reading {fileType}: {ex.Message}"); } } // 显示最终统计结果 errorMessage.AppendText($"\r\n\r\nTotal matched entries: {matchedCount}"); } // 假设你的brians函数定义如下(需根据实际逻辑实现) private string GetPylonFromReceiverPin(string receiverPin) { // 这里替换为实际的业务逻辑 return "Pylon_" + receiverPin; }
关键代码说明
- 集合化路径管理:用
List<string>存储三个文件路径,通过foreach循环统一处理,避免重复编写三次相同逻辑。 - 无效路径过滤:遇到空路径直接跳过,避免无意义的文件检查操作。
- 安全文件读取:用
File.ReadLines逐行读取文件,内存占用更低;添加try-catch捕获读取时的异常(如权限不足、文件损坏)。 - 智能内容分割:使用
StringSplitOptions.RemoveEmptyEntries,分割时自动忽略连续空格产生的空元素,避免后续逻辑出错。 - 业务逻辑预留:注释部分标注了验证逻辑的位置,可根据实际文件的列索引调整代码。
额外优化建议
- 给文件选择对话框添加过滤器,限制仅能选择文本文件:
openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"; - 若文件体积较大,建议使用
async/await异步读取文件,避免UI线程卡顿:foreach (var line in await File.ReadAllLinesAsync(filePath)) { // 处理逻辑不变 }
内容的提问来源于stack exchange,提问作者user21228079
相关产品推荐
相关产品推荐

