所以,我写了一些代码,假设读取一个文本文件,然后检查特定字符串的实例。如果该字符串存在,它将需要执行一个操作。我添加了一些消息框,让我知道功能的进度。问题是,它没有找到这个词。这是我的代码:
private void test2_Click(object sender, EventArgs e)
{
StreamReader objReader = new StreamReader("C:\\testing\\mslogon.log");
string sLine = "";
ArrayList arrText = new ArrayList();
MessageBox.Show("File Read");
while (sLine != null)
{
sLine = objReader.ReadLine();
if (sLine != null)
{
arrText.Add(sLine);
}
}
if (arrText.Contains("Invalid"))
{
MessageBox.Show("Word Invalid Found");
}
else
{
MessageBox.Show("Nada");
}
}
最佳答案
现在,您正在检查 arrText 中是否存在恰好等于“无效”的元素。如果“Invalid”嵌入到某个更大的字符串中,它将找不到它。
要检查是否有任何字符串包含 Invalid,您必须这样做:
foreach(var line in arrText)
{
if (line.Contains("Invalid")) { MessageBox.Show("Word 'Invalid' Found"); break; }
}
使用@Alexei 提到的 File.ReadAllText 可以让你做一些你想做的事情,看起来像这样:
String wholeFile = File.ReadAllText();
if (wholeFile.Contains("Invalid")) {
MessageBox.Show("Word 'Invalid' Found");
} else {
. . .
关于c# - 用于在文本文件中搜索确切字符串并在找到失败时执行操作的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39044468/