【问题标题】:CS1929 - Trying to read a file, and skip to the line that contains a certain string and return that line's contentCS1929 - 尝试读取文件,并跳到包含特定字符串的行并返回该行的内容
【发布时间】:2021-11-24 00:00:37
【问题描述】:

错误发生在 SkipWhile 方法中,在第二个“line”关键字中。显示以下日志

CS1929 "char" 不包含 "Contains" 的定义,并且最佳扩展方法重载 "Queryable.Contains(IQueryable, string)" 需要 "IQueryable" 类型的接收器

    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);

        if (File.ReadAllText(path).Contains(user))
        {

            employee.Registration = File.ReadAllText(path).SkipWhile(line => !line.Contains(user))
            .TakeWhile(line => !line.Contains(user));
        }
        else
        {
            MessageBox.Show("Invalid User or Password..", "Invalid Login", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }
    }

【问题讨论】:

  • ReadAllText 返回 1 个字符串,而不是行列表
  • ReadAllText 将文件的全部内容作为单个字符串提供给您。如果您想使用线条,我可能会建议您考虑改用ReadAllLines。此外,与其读取文件的全部内容两次,不如直接跳转到您的 SkipWhile/TakeWhile 代码,然后检测它是否没有返回任何行。
  • 听起来是一种非常不安全的安全测试方式——如果输入文本包含用户名 FOOBAR 并且测试的用户名是 FOO 或 BAR,则在测试用户时会发现两者。我知道这不是你的问题。
  • 这不是很安全,但它只是一个原型。谢谢你的评论。我再看看这个。

标签: c#


【解决方案1】:

您正在使用File.ReadAllText,然后使用SkipWhile 将返回文本的每个字符。您应该使用File.ReadLines 并遍历这些行。

employee.Registration = File.ReadLines(path).SkipWhile(line => !line.Contains(user))
        .TakeWhile(line => !line.Contains(user));

另外,我认为您的.TakeWhile(line => !line.Contains(user) 是错误的,它不应该尝试匹配user 而不是不匹配吗?

employee.Registration = File.ReadLines(path).SkipWhile(line => !line.Contains(user))
        .TakeWhile(line => line.Contains(user));

【讨论】:

  • 嘿。这不是完全正确的答案,但它让我走上了通往正确答案的道路。谢谢。此外,“.TakeWhile()”实际上是错误的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 2012-09-09
  • 2019-08-30
  • 2022-09-24
  • 1970-01-01
相关资源
最近更新 更多