2017-01-01 125 views
-3

真的是C#的新手。我需要搜索关键字的文本文件。如果在搜索完整个文件后,发现关键字弹出消息框。如果在搜索完整个文件后,找不到关键字弹出消息框。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

因此,只需使用['ReadToEnd'](https://msdn.microsoft.com/en-us/library/system.io.streamreader.readtoend(v = vs.110).aspx)读取整个文件? – UnholySheep

+3

你有什么尝试?您可以考虑不立即显示消息框,但将结果保存在循环后检查的变量中。 – CodeCaster

+0

您应该考虑加载文件并在其中异步搜索(线程,线程池,backgroundworker或更好的异步/等待机制)。 – honzakuzel1989

回答

0

File.ReadAllText是更适合的是,你可以在所有文本一次在一个字符串阅读:

string file = File.ReadAllText("path"); 

if (file.Contains(keyword))  { 
//.. 
} 
else { 
//.. 
} 

或一条线:

if (File.ReadAllText("path").Contains("path")) { 
} 
else { 
} 

陈述一样在评论中,您可能会耗尽内存来查看非常大的文件,但对于正常的日常使用,这种情况不会发生。

+1

应该被添加,这是不适合大文件 –

+2

你告诉刚刚开始编程的人_“使用此代码而不是_”,而不解释_why_他们应该使用代码,也没有说这些代码的缺点是什么。 – CodeCaster

+0

谢谢ServéLaurijssen,效果很棒! – Malasorte

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!"); 
}