2014-11-15 76 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");