2009-08-27 132 views
0

我想在使用StreamReader.WriteLine()獲取數據後刪除txt文件中的一行。 但我不能得到任何有用的網站參考。 有人告訴我,我可以用Repalce()方法做到這一點,但我不認爲它的效率。 任何人都可以告訴我如何解決它。謝謝!C#:刪除Txt文件中的一行

+0

把它作爲不夠有效的方法的原因是什麼? –

回答

4

您無法刪除文件中間的內容。你必須從這一點重寫所有內容,或者重寫整個文件。如果您使用StreamReader/StreamWriter,那麼您無權訪問文件位置,因此您唯一的選擇是重寫整個文件。

下面是一個如何做到這一點的示例方法。

public static void RemoveLines(Predicate<string> removeFunction,string file){ 
     string line, tempFile = null; 
     try{ 
      tempFile = Path.GetTempFileName(); 
      using (StreamReader sr = new StreamReader(file)) 
      using (StreamWriter sw = new StreamWriter(tempFile,false,sr.CurrentEncoding)) 
       while ((line = sr.ReadLine()) != null) 
        if (!removeFunction(line)) sw.WriteLine(line); 
      File.Delete(file); 
      File.Move(tempFile, file); 
     }finally{ 
      if(tempFile != null && File.Exists(tempFile)) 
       File.Delete(tempFile); 
     } 
    } 

像這樣來使用

RemoveLines(line=>line.Length==10,"test.txt") 

它消除所有10個字符的長度線,並且使用一個臨時文件,以儘量減少所涉及的風險。當然,如果你想要更短的東西,你可以做這樣的事情。

File.WriteAllLines(fileName,File.ReadAllLines(fileName).Where(line => line.Length != 10)) 

需要更多的工作記憶,你可能應該做的臨時文件/移動把戲對衝電腦死機造成損壞的文件。但它是緊湊且易於理解的代碼。