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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM