将行添加到文件中心

时间:2014-11-15 16:45:32

标签: c# .net file

我的文件包含以下内容:

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 +1元素保存所有行(让我告诉,有 n 行)到数组把它们等等等等。

作为技术细节,我可以告诉我使用System.IO.StreamWriterSystem.IO.File

SO上的搜索引擎没有给出我想看的结果...... C#Reference也没有给出预期的结果。

2 个答案:

答案 0 :(得分:0)

您无法插入到文件中。您可以附加到现有或写一个新的。因此,您需要阅读它,然后重新编写它,将文本快速插入到您想要的位置。

如果文件很小,您可能希望使用File类的静态函数一步读取和写入。

答案 1 :(得分: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");