2014-11-15 126 views
0

中心我有以下內容的文件:添加一行到文件

This line number 1 
I like playing football 
This is the end 

我只想第二行之後添加文本行:

This line number 1 
I like playing football 
I like eating pasta <------ this line shall be added 
This is the end 

是否有其他更簡單這樣做比保存所有行(讓我告訴,有n行)與n +1元素並將它們向下移動等。

作爲技術細節,我可以告訴我使用System.IO.StreamWriterSystem.IO.File

SO上的搜索引擎沒有給出我想看到的結果...... C#Reference也沒有給出預期的結果。

回答

0

你不能插入到文件中。您可以附加到現有的或寫入一個新的。所以你需要閱讀它,然後再寫一遍,在你想要的地方插入你的文本。

如果文件很小,您可能需要使用File類的靜態函數來一步讀取和寫入它。

0

如果我理解你的問題,你正在尋找一個比調整數組大小更簡單的方法並將每條線向下移動? (這是不可能插入新行,無需重新寫入文件)

你可以做它行加載到List,並通過使用List.InsertExample

插入第二個索引處的新行

例如:

List<string> lines = new List<string>(); 

// Read the file and add all lines to the "lines" List 
using (StreamReader r = new StreamReader(file)) 
{ 
    string line; 
    while ((line = r.ReadLine()) != null) 
    { 
     lines.Add(line); 
    } 
} 

// Insert the text at the 2nd index 
lines.Insert(2, "I like eating pasta");