C#向现有的文本文件中插入数据

来源:百度知道 编辑:UC知道 时间:2024/05/10 19:42:20
能不能像现有的文本文件中写东西
在文本文件指定的行中
比如,
向现有的文本文件的第十行插入数据
能不能给个源码看看
谢谢

class Program
{
static void Main(string[] args)
{
Console.WriteLine("输入要读取的文件名(全路径):");
string strFile = Console.ReadLine().Trim();

System.IO.StreamReader sr = new System.IO.StreamReader(strFile);
Console.WriteLine("在多少行插入文本:");
int iLine = Int32.Parse(Console.ReadLine());

Console.WriteLine("插入什么文本:");
string strInsert = Console.ReadLine();

string strText = ""; //用来存储更改后的文本内容
int lines = 0; //记录文件行数
while (!sr.EndOfStream)
{
lines++;
if (lines == iLine)
{
strText += strInsert + "\n";
}
string str = sr.ReadLine();
strText += str + "\n";
}
if (lines < iLine) //输入的行号比文件总行数大
{
Console.WriteLine("\n输入的行号非法!");
}
else
{
Console.WriteLine("\n插入后文件的内容:\n==================