2012-12-19 41 views
-3

我想讓我的代碼過濾,並從txt文件中的特定單詞開始和結束。C#讀取和過濾文本

對,對不起。問題是,如何告訴它從一條線開始並停止另一條線?

foreach (string line in File.ReadLines(@"C:\test.txt")) 
{ 
    if (line.Contains("text")) 
    { 
    Console.WriteLine(line); 
    } 
} 

我將tr指定我打算實現的目標。

它必須從「命令:更新」行開始並結束。棘手的部分是,它必須從最後一個「命令:更新」開始。

Command    : Update 
Updating    : C:\somepath\somepath\somefile1.doc 
Completed   : C:\somepath\somepath\somefile1.exe 
External    : C:\somepath\somepath\somefile1.fla 
Completed   : C:\somepath\somepath\somefile1.txt 
Completed   : C:\somepath\somepath\somefile1.doc 
Completed   : C:\somepath\somepath\somefile1.exe 
Command    : Update 
Updating    : C:\somepath\somepath\somefile222.fla 
External    : C:\somepath\somepath\somefile222.txt 
Updating    : C:\somepath\somepath\somefile222.doc 
Completed   : C:\somepath\somepath\somefile222.exe 
External    : C:\somepath\somepath\somefile222.fla 
Completed   : C:\somepath\somepath\somefile222.txt 
Completed   : C:\somepath\somepath\somefile222.doc 
Completed   : C:\somepath\somepath\somefile222.exe 

的preferd輸出將

C:\somepath\somepath\somefile222.doc 
C:\somepath\somepath\somefile222.doc 
+5

問題是什麼? –

+0

你能否澄清你想要做什麼以及哪些不能在你的代碼中工作? –

+0

問題是?請澄清你正在嘗試做什麼,究竟是什麼問題。 – SWeko

回答

1

這是不是最好的代碼,並很可能被清理了一些,但這應該讓你開始。該代碼將讀取尋找指示開始寫入的文本的行。然後它會輸出行,直到找到指示完成寫入的文本。在這一點上,它不會再讀取任何行並退出循環。

bool output = false; 
foreach (var line in File.ReadLines("C:\\test.txt")) 
{ 
    if (!output && line.Contains("beginText")) 
    { 
     output = true; 
    } 
    else if (output && line.Contains("endText")) 
    { 
     break; 
    } 

    if (output) 
    { 
     Console.WriteLine(line); 
    } 
} 

編輯基於問題的更新:

我將離開過濾出來的結果行的你,因爲我不知道規則是什麼定義應該是什麼輸出,什麼不該'噸,但這是至少得到最後更新行後的結果的方法:

var regex = new Regex(@"Command\s+:\s+Update"); 
List<string> itemsToOutput = null; 
foreach(var line in File.ReadLines("C:\\test.txt")) 
{ 
    if (regex.IsMatch(line)) 
    { 
     itemsToOutput = new List<string>(); 
     continue; 
    } 

    if (itemsToOutput != null) 
    { 
     itemsToOutput.Add(line); 
    } 
} 
+0

這似乎是什麼運算需要.. +1 – Default

+0

謝謝,再接近一步 – itIsMeBen

+0

@itIsMeBen - 隨時upvote然後:)一旦你有輸出行的列表,它應該是微不足道的過濾出行和分割文本,讓你得到的只是文件名。如果你列出了什麼定義了你對輸出列表的過濾,我可以進一步提供幫助。有很多規則可以用來獲得您的「首選輸出」。 – pstrjds