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