2012-05-16 40 views
0

我有我的項目寫入兩個文本文件。一個用於輸入,另一個用於輸出。 我最終需要他們寫入兩個相同的文本文件。如何從文本文件中去除不需要的行

這裏是到目前爲止我的代碼:

static void Main(string[] args) 
    { 
     string line = null; 
     string line_to_delete = "--"; 
     string desktopLocation = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); 
     string text = Path.Combine(desktopLocation, "tim3.txt"); 
     string file = Path.Combine(desktopLocation, "tim4.txt"); 

     using (StreamReader reader = new StreamReader(text)) 
     { 
      using (StreamWriter writer = new StreamWriter(file)) 
      { 
       while ((line = reader.ReadLine()) != null) 
       { 
        if (string.Compare(line, line_to_delete) == 0) 
         File.WriteAllText(file, File.ReadAllText(text).Replace(line_to_delete, "")); 
        continue; 
       } 
      } 

感謝

+0

你有在輸出輸入一個文本文件,一個和你想把它們寫到同一個文本文件中?你什麼意思? –

+0

是的,我有兩個文本文件。輸入文件和輸出文件。 –

+0

@ Artic-M00n我認爲你需要重新閱讀你的問題,因爲它沒有明確的措辭。 「寫入同一個文本文件」沒有意義 –

回答

3

如果你想從輸入讀取文件中的所有行,並將它們全部用線除外寫入到輸出文件匹配給定的文本:

public static void StripUnwantedLines(
    string inputFilePath, 
    string outputFilePath, 
    string lineToRemove) 
{ 
    using (StreamReader reader = new StreamReader(inputFilePath)) 
    using (StreamWriter writer = new StreamWriter(outputFilePath)) 
    { 
     string line; 
     while ((line = reader.ReadLine()) != null) 
     { 
      bool isUnwanted = String.Equals(line, lineToRemove, 
       StringComparison.CurrentCultureIgnoreCase); 

      if (!isUnwanted) 
       writer.WriteLine(line); 
     } 
    } 
} 

在這種情況下,使用當前的文化進行比較(它可能並不重要,如果你需要搜索「 - 」,但很明顯需要指定)並且不區分大小寫。
如果您希望跳過以給定文本開頭的所有行,則可能需要更改String.Equalsline.StartsWith

鑑於此輸入文件:

 
This is the begin of the file 
-- 
A line of text 
-- 
Another line of text 

它會產生這樣的輸出:

 
This is the begin of the file 
A line of text 
Another line of text 

注意
在您的例子中,你使用的while循環內部這段代碼:

File.WriteAllText(file, 
    File.ReadAllText(text).Replace(line_to_delete, "")); 

沒有其他任何東西就足夠了(但它會刪除不需要的行,用空的行替換它們)。它的問題(如果保留空行不是問題)是它會讀取內存中的整個文件,如果文件非常大,它可能非常慢。 只是爲了信息,這是你會如何改寫它做同樣的任務(不太大文件,因爲它在內存中):

File.WriteAllText(outputFilePath, File.ReadAllText(inputFilePath). 
    Where(x => !String.Equals(x, lineToDelete)); 
相關問題