首页 > 解决方案 > 如果文件中没有特定的字符串,我正在尝试报告一条消息。我不断收到相同的消息

问题描述

我正在阅读一个文本文件。如果文件中没有特定的字符串,我正在尝试报告一条消息。我不断收到同样的信息,或者,完全不取决于我把它放在哪里。

我已经移动了这个(代码就在柜台++上方;靠近底部)“else lbOne.Items.Add(txtID.Text +”不存在。“);” 在没有运气的情况下绕到每条可以想象的路线。我知道这足够危险,所以可以使用一些帮助。

    if (rButtonFind.Checked)
        {
            int counter = 0;
            string line;
            System.IO.StreamReader file = new System.IO.StreamReader(@"F:\Quality\CMM Fixtures\fixtures.txt");

            if (new FileInfo(@"F:\09 Quality\CMM Fixtures\fixtures.txt").Length == 0)
            {
                MessageBox.Show("There is no data in the file to search." + "\n" + "There must be at least one fixture" + "\n" + " to not see this message.");
            }

                while ((line = file.ReadLine()) != null)
                {
                    if (line.Contains(txtID.Text))
                    {
                        lbOne.Items.Add(line);
                    }
                    else
                    lbOne.Items.Add(txtID.Text + " does not exist.");
                    counter++;
                }           

                file.Close();                
            }         
        }

正如我所说,它要么多次列出“不存在”消息,要么根本不列出。

标签: c#loopsif-statementwhile-loop

解决方案


由于您只需要知道文件是否包含至少一次出现的字符串,那么这就是您需要的代码。但是您还需要更好地防御不存在的文件。

我不知道是否counter应该是读取的行数,或者是否应该指示未找到字符串的次数。我只是假设这是找不到字符串的次数。但无论如何,范围counter是在if块内,所以它没有用,除非你打算以后用它做点什么,在这种情况下你必须改变它的范围。

if (rButtonFind.Checked) {
   int counter = 0;
   string line;
   string filename = @"F:\Quality\CMM Fixtures\fixtures.txt";
   System.IO.StreamReader file = new System.IO.StreamReader(filename);
   if (new FileInfo(filename).Length == 0) {
      MessageBox.Show("There is no data in the file to search." + "\n" + "There must be at least one fixture" + "\n" + " to not see this message.");
   } else {
      bool found = false;
      while ((line = file.ReadLine()) != null) {
         if (line.Contains(txtID.Text)) {
            lbOne.Items.Add(line);
            found = true;
            break;
         }
      }
      if (!found) {
         lbOne.Items.Add(txtID.Text + " does not exist.");
         counter++;
      }
   }
   file.Close();
}

推荐阅读