检查文件中是否存在字符串 [英] check if string exists in a file
本文介绍了检查文件中是否存在字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下一段代码,它打开一个文本文件并读取文件中的所有行并将其存储到一个字符串数组中.
I have the following piece of code which opens a text file and reads all the lines in the file and storing it into a string array.
然后检查字符串是否存在于数组中.然而,我面临的问题是,无论何时找到一个字符串,它总是显示有匹配" 以及没有匹配".知道如何解决这个问题吗?
Which then checks if the string is present in the array. However the issue I'm facing is that whenever a string is found, it always shows "there is a match" as well as "there is no match". Any idea how to fix this?
检查此代码:
using (StreamReader sr = File.OpenText(path))
{
string[] lines = File.ReadAllLines(path);
for (int x = 0; x < lines.Length - 1; x++)
{
if (domain == lines[x])
{
sr.Close();
MessageBox.Show("there is a match");
}
}
if (sr != null)
{
sr.Close();
MessageBox.Show("there is no match");
}
}
推荐答案
我建议如下设置和标记并检查它...
I would recommend seting and flag and checking it as follows...
using (StreamReader sr = File.OpenText(path))
{
string[] lines = File.ReadAllLines(path);
bool isMatch = false;
for (int x = 0; x < lines.Length - 1; x++)
{
if (domain == lines[x])
{
sr.Close();
MessageBox.Show("there is a match");
isMatch = true;
}
}
if (!isMatch)
{
sr.Close();
MessageBox.Show("there is no match");
}
}
祝你好运!
这篇关于检查文件中是否存在字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文