C#真的很新。我需要在文本文件中搜索关键字。如果在搜索完整个文件后 ,则会在弹出的消息框中找到该关键字。如果在搜索整个文件后 ,则找不到关键字弹出消息框。
到目前为止,我有以下内容。问题是它逐行读取文件。如果在第一行中未找到关键字,则会显示警告“未找到”。然后转到下一行并再次显示“未找到”。等等。我需要脚本来搜索整个文件,然后只显示“未找到”一次。谢谢!
private void SearchButton_Click(object sender, EventArgs e)
{
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
String line;
String[] array;
while ((line = file.ReadLine()) != null)
{
if (line.Contains("keyword"))
{
MessageBox.Show("Keyword found!");
}
else
{
MessageBox.Show("Keyword not found!");
}
}
}
答案 0 :(得分:1)
尝试使用File
类而不是读者(必须使用Dispose
以防止资源泄漏):
bool found = File
.ReadLines("c:\\test.txt") // Try avoid "All" when reading: ReadAllText, ReadAllLines
.Any(line => line.Contains("keyword"));
if (found)
MessageBox.Show("Keyword found!");
else
MessageBox.Show("Keyword not found!");
您的代码已修改(如果您坚持StreamReader
):
private void SearchButton_Click(object sender, EventArgs e) {
// Wra IDisposable (StreamReader) into using in order to prevent resource leakage
using (file = new StreamReader("c:\\test.txt")) {
string line;
while ((line = file.ReadLine()) != null)
if (line.Contains("keyword")) {
MessageBox.Show("Keyword found!");
return; // Keyword found, reported and so we have nothing to do
}
}
// File read with no positive result
MessageBox.Show("Keyword not found!");
}
答案 1 :(得分:0)
File.ReadAllText更适合这种情况,您可以在一个字符串中一次性读取所有文本:
string file = File.ReadAllText("path");
if (file.Contains(keyword)) {
//..
}
else {
//..
}
或一行:
if (File.ReadAllText("path").Contains("path")) {
}
else {
}
如评论中所述,对于非常大的文件,您可能会耗尽内存,但对于正常的日常使用,这种情况不会发生。