You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 04:35:03