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

CS1929报错:读取文件跳转至含指定字符串行时SkipWhile出现char无Contains定义错误

错误产生原因

CS1929 "char" does not contain a definition for "Contains" and the best extension method overload "Queryable.Contains(IQueryable, string)" requires a receiver of type "IQueryable"

该错误的触发核心是调用方法的对象类型不匹配:

  • File.ReadAllText() 方法返回值是单个字符串,字符串本身实现了IEnumerable<char>接口,直接对其调用SkipWhile方法时,迭代遍历的元素是单个char字符,你Lambda表达式中声明的line参数实际是char类型,不存在接收字符串参数的Contains方法,因此触发类型不匹配错误。
  • 额外存在逻辑缺陷:就算类型匹配,你当前写的SkipWhile(line => !line.Contains(user)).TakeWhile(line => !line.Contains(user))逻辑也无法拿到包含指定用户的行,跳过不含用户的行之后又筛选不含用户的行,最终只会拿到空结果。
修复方案

你需要切换为按行读取文件的API,同时调整取值逻辑,优化后还解决了原代码重复读取文件的IO浪费问题:

  1. 使用File.ReadAllLines()方法读取文件,返回值为字符串数组,每个元素对应文件的一行内容,保证迭代对象为整行字符串
  2. 单次读取文件内容存储到变量中,避免重复执行磁盘IO操作
  3. 直接使用FirstOrDefault()匹配第一个包含目标用户的行即可

修复后的完整代码如下:

public static void loginEmployee(string user, string password)
{
    string filename = "servidores_cadastrados_db_backup.txt";
    string path = AppConfig.appconfig.defaultPath;
    path = Path.Combine(path, filename);

    // 单次读取所有行,避免重复IO
    var allLines = File.ReadAllLines(path);
    
    if (allLines.Any(line => line.Contains(user)))
    {
        // 取第一个包含目标用户的行
        employee.Registration = allLines.FirstOrDefault(line => line.Contains(user));
        // 注意:你当前未实现password参数的校验逻辑,需后续补充避免登录逻辑漏洞
    }
    else
    {
        MessageBox.Show("Invalid User or Password..", "Invalid Login", MessageBoxButtons.OK,
            MessageBoxIcon.Error);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:24:09