c# - 如果文件中没有特定的字符串,我正在尝试报告一条消息。我不断收到相同的消息
问题描述
我正在阅读一个文本文件。如果文件中没有特定的字符串,我正在尝试报告一条消息。我不断收到同样的信息,或者,完全不取决于我把它放在哪里。
我已经移动了这个(代码就在柜台++上方;靠近底部)“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();
}
}
正如我所说,它要么多次列出“不存在”消息,要么根本不列出。
解决方案
由于您只需要知道文件是否包含至少一次出现的字符串,那么这就是您需要的代码。但是您还需要更好地防御不存在的文件。
我不知道是否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();
}
推荐阅读
- r - R包DT无法安装
- c# - c#将任何类型转换为二进制形式的字符串或整数数组
- substrate - 有哪些可用的股权证明 [PoS] 算法
- python - 我无法自动化不和谐 webhook python
- python - 如何更改注释分布图?
- sql - SQL Server:更新参与分组的行
- javascript - 如何使用角度在 ng 图表中为图例添加前缀
- javascript - 如何在元素的点击时将 id 从一个组件传递到另一个组件
- api - Symfony 5 Exception 上的 FosRestBundle 不起作用
- oracle-apex - 顶点按钮在另一个工作区的另一个应用程序中调用页面?