2011-10-09 113 views
0

我正在嘗試編輯c#中的文本文件。該文本文件在以前的形式創建,幷包括以下內容:使用c編輯文本文件中的特定行#

Date Of Birth = 01/01/1980 
Age = 31 
Total = 40985 
required1 = 
required2 = 
required3 = 

這個文本文件只有13線長,基本上我想忽略前三行,然後編輯以下10條線路。我最初試圖用下面的代碼,但明顯的缺陷被附加到文件:

List<string> newlines = new List<string>(); 
newlines.Add(Convert.ToString(required1)); 
newlines.Add(Convert.ToString(required2)); 
newlines.Add(Convert.ToString(required3)); 

System.IO.File.AppendAllLines(filepath); 

我使用的StreamReader讀取所有行,但如何編輯第三行開始是一個謎思,是我新的使用C#的任何幫助,非常感謝。

回答

2

由於您的文件很小,您可以將其全部加載到內存中。然後使用它並保存它,完全覆蓋整個文件:

string[] lines = File.ReadAllLines(fileName); 

// modify the lines 

File.WriteAllLines(fileName, lines); 
+0

這很棒,太簡單了,謝謝。 – Rg786