//思路:將文件一行一行讀出來存到一個變量中, 當到要插入的行時將插入內容拼到變量中, 最后將變量值重新寫到文件中。 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();
