【问题标题】:NullReferenceException when comparing string read in from a file?比较从文件中读取的字符串时出现 NullReferenceException?
【发布时间】:2012-05-02 23:11:25
【问题描述】:

我有一个以“a a”作为用户名和密码的clients.txt 文件。如果我没记错的话,这应该从中读取并告诉我它们是否存在于文件中。

编辑:在 clients.txt 文件的第二行,我有“b b”作为用户名和密码,它们工作正常。

这里的图片:(新用户不能发图片)

    StreamReader sr = new StreamReader("clients.txt");
    int findIndex = -1;
    string userpass = "#";
    while (findIndex == -1 && sr.ReadLine() != null)
    {
        findIndex = userpass.IndexOf(txtUserName.Text + " " + txtPassword.Password);
        userpass = sr.ReadLine();
    }
    sr.Close();

【问题讨论】:

  • 要去看看一些代码。作为文本 - 请不要使用代码图像。
  • 由于调试器正在捕获异常,您应该能够查看该行上的控件和变量,看看哪一个为空。
  • 好地方@dash - 没看到.Password!那也无济于事! :o)
  • @ChrisRoberts 我不确定这里使用的是什么控件 - 如果它是一个文本框,那么即使它编译我也会感到惊讶。 FWIW 你已经把它钉在了第一行之后。通常,人们检查 while(!sr.EndOfStream) { userPass = sr.ReadLine(); ...}
  • 这就是我们处理敏感用户信息的那种代码?

标签: c# file-io streamreader


【解决方案1】:

您的 while() 语句正在吞噬行。您需要在正文中移动 ReadLine() 调用:

    while (findIndex == -1) {
        userpass = sr.ReadLine();
        if (userpass == null) break;
        findIndex = userpass.IndexOf(txtUserName.Text + " " + txtPassword.Password);
    }

不要将密码以明文形式放在文本文件中。

【讨论】:

    【解决方案2】:

    在 while 语句中对 sr.Readline 的调用将读取(并忽略)文本文件的第一行,因此在第二次调用 sr 之后,被比较的第一行将是文本文件的第二行。读线。

    您需要重构您的代码,以便始终捕获来自对 sr.ReadLine 的调用的响应。

    【讨论】:

      猜你喜欢
      • 2017-08-20
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多