C#读取文件搜索姓名仅能获取第一条数据,求排查Bug
问题分析与修复方案
核心Bug定位
你的代码中读取数据文件的循环步长设置错误,这是导致仅能获取第一个用户数据的直接原因:
- 数据文件里每个用户的信息占2行:第一行是姓名,第二行是逗号分隔的详细信息
- 你当前循环使用
i += 6,意味着每间隔6行才处理一个用户,但你的数据文件总共只有6行,循环仅执行一次就终止,因此只能读取到第一个用户John的数据。
修复后的代码片段
修改InitializeData方法中的循环步长,将i += 6改为i += 2:
private void InitializeData() { // Read data from the text file and populate the peopleList peopleList = new List<Person>(); try { string[] lines = File.ReadAllLines("people_data.txt"); // 修正步长为2,对应每个用户的两行数据 for (int i = 0; i < lines.Length; i += 2) { string name = lines[i]; string[] info = lines[i + 1].Split(','); string telephone = info[0].Trim(); int age = int.Parse(info[1].Trim()); string address = info[2].Trim(); string nationality = info[3].Trim(); DateTime birthday = DateTime.ParseExact(info[4].Trim(), "dd.MM.yyyy", null); Person person = new Person(name, telephone, age, address, nationality, birthday); peopleList.Add(person); } } catch (Exception ex) { MessageBox.Show("Error reading data from file: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
额外优化建议(可选)
- 添加对空行的判断,避免文件中存在空行时出现索引越界错误:
for (int i = 0; i < lines.Length; i += 2) { // 跳过空行 if (string.IsNullOrWhiteSpace(lines[i])) { i--; // 调整索引,避免跳过有效数据 continue; } // 后续处理逻辑不变 } - 对
int.Parse和DateTime.ParseExact添加单独的异常捕获,方便定位具体的数据格式错误。
内容的提问来源于stack exchange,提问作者hajmanga
相关产品推荐
相关产品推荐

