将行添加到文件中心
本文关键字:文件 添加 | 更新日期: 2023-09-27 18:30:27
我有包含以下内容的文件:
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.StreamWriter
和System.IO.File
。
SO 上的搜索引擎没有给出我想看到的结果......C# 参考也没有给出预期的结果。
不能插入到文件中。您可以追加到现有或写入新内容。所以你需要阅读它,然后再次写,在你想要的地方即时插入你的文本。
如果文件很小,您可能希望使用 File
类的静态函数一步读取和写入它。
如果我理解您的问题,您正在寻找一种比调整数组大小并将每一行向下移动更简单的方法?(如果不重写文件,则无法插入新行)
你可以做什么 将行加载到List
中,并使用List.Insert
在第二个索引处插入新行(示例)
例:
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");