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

C# WinForm用户名去重功能失效,仅检测文本文件首行求助

问题根源

你的注册验证逻辑只读取了文件的第一行就结束检查,没有遍历文件中所有用户记录,导致只有第一行的用户名能被检测到重复,后续行的用户名完全没被校验。

修正后的代码
private void btnregister2_Click(object sender, EventArgs e)
{
    // 先检查必填项是否为空,提前拦截无效操作
    if (string.IsNullOrEmpty(txtlastname.Text) || 
        string.IsNullOrEmpty(txtfirstname.Text) || 
        string.IsNullOrEmpty(txtusername2.Text) || 
        string.IsNullOrEmpty(txtpassword2.Text) || 
        string.IsNullOrEmpty(cmbaccounttype.Text))
    {
        MessageBox.Show("ERROR! There is an empty text.");
        return;
    }

    string targetUsername = txtusername2.Text.Trim(); // 去除首尾空格,避免空格导致的误判
    bool usernameExists = false;

    // 使用using自动管理流资源,无需手动Close
    using (StreamReader fReader = new StreamReader("UserAccount.txt"))
    {
        string fLine;
        // 循环读取每一行,直到文件末尾
        while ((fLine = fReader.ReadLine()) != null)
        {
            // 分割行内容,先判断数组长度是否符合预期,避免索引越界
            string[] fContent = fLine.Split('|');
            if (fContent.Length >= 3) // 确保用户名所在的索引位置有效
            {
                if (fContent[2].Trim().Equals(targetUsername, StringComparison.OrdinalIgnoreCase))
                {
                    usernameExists = true;
                    break; // 找到重复用户名,直接跳出循环
                }
            }
        }
    }

    if (usernameExists)
    {
        MessageBox.Show("username already exists!");
    }
    else
    {
        // 追加写入用户记录,自动管理流资源
        using (StreamWriter record = new StreamWriter("UserAccount.Txt", true))
        {
            record.WriteLine($"{txtlastname.Text.Trim()}|{txtfirstname.Text.Trim()}|{targetUsername}|{txtpassword2.Text.Trim()}|{cmbaccounttype.Text.Trim()}");
        }
        MessageBox.Show("Account successfully registered!");
        cleanup();
    }
}
关键改进点
  • 遍历所有行:用while循环读取文件每一行,确保检查所有已存在的用户名
  • 提前空值校验:先检查必填项是否为空,避免不必要的文件IO操作
  • 自动资源管理:用using语句包装流对象,自动释放文件资源,避免手动关闭流导致的资源泄漏
  • 安全的字符串处理:
    • 对输入和文件中的用户名去除首尾空格,避免因空格导致重复判断失效
    • 判断分割后的数组长度,防止文件格式异常时出现索引越界错误
    • 可选忽略大小写的用户名比较(如需严格大小写校验,将StringComparison.OrdinalIgnoreCase改为StringComparison.Ordinal即可)
  • 优化性能:找到重复用户名后立即跳出循环,减少不必要的读取操作

内容的提问来源于stack exchange,提问作者tin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:45:32