日期:2014-05-18  浏览次数:20892 次

用C#操作文件,如何在txt文件中的指定一行 写入数据? 求助,在线等
用C#操作文件,如何在txt文件中的指定一行 写入数据?
求助

------解决方案--------------------
我的思路:
将文件一行一行读出来存到一个变量中, 当到要插入的行时将插入内容拼到变量中, 最后将变量值重新写到文件中。

C# code

string sTestFileName = @"e:\t1.txt";
int iInsertLine = 5;
string sInsertText = "插入的内容";
string sText = "";
System.IO.StreamReader sr = new System.IO.StreamReader(sTestFileName);

int iLnTmp = 0; //记录文件行数
while (!sr.EndOfStream)
{
    iLnTmp++;
    if (iLnTmp == iInsertLine)
    {
        sText += sInsertText + "\r\n";  //将值插入
    }
    string sTmp = sr.ReadLine();    //记录当前行
    sText += sTmp+"\r\n";
}
sr.Close();

System.IO.StreamWriter sw = new System.IO.StreamWriter(sTestFileName, false);
sw.Write(sText);
sw.Flush();
sw.Close();