我使用下面的方法來分析一個文本文件,並編寫包含特定關鍵字行下面一行:搜索關鍵詞,打印線和
using (StreamReader sr = new StreamReader("C:/Users/Downloads/apple.txt"))
{
string appleLine;
bool lastLine = false;
// currentLine will be null when the StreamReader reaches the end of file
while ((appleLine = sr.ReadLine()) != null)
{
// Search, case insensitive, if the currentLine contains the searched keyword
if (appleLine.IndexOf("Apple", StringComparison.CurrentCultureIgnoreCase) >= 0 || lastLine)
{
Console.WriteLine(appleLine);
Console.WriteLine();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Downloads\parsed.txt", true))
{
file.WriteLine(appleLine);
file.WriteLine();
}
lastLine = true;
}
if (lastLine)
{
lastLine = false;
}
}
在apple.txt我有事像這樣:
---一號線蘋果MacBook Pro ---
--- 2號線www.newegg.com ---
但這並不打印出與URL行(行2) 。 apple.txt文件可能有200行。
非常感謝您的幫助!
這一個工作;) – tedder84