this.治疗完毕

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#读取TXT文本指定行的语句

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

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();

 

posted on 2018-05-31 14:46  this.治疗完毕  阅读(7270)  评论(0)    收藏  举报