C#操作txt文件
在C#中实现操作txt文件,今天因功能需要,实现了在txt文件的指定位置插入指定的内容,代码如下:
1.以下代码是在指定位置插入特定内容(在指定行后面添加新的一行,在指定的字符后面添加特定内容)
/// <summary> /// Insert information to txt file of the path /// </summary> /// <param name="path">the path of txt file</param> /// <param name="alias">the lower of information</param> private void InsertInfoToFile(string path, string information) { string alias = information.ToLower(); //transfer the upper character in information to lower string sInsertText = alias + " = (" + information + ")"; string sText = ""; System.IO.StreamReader sr = new System.IO.StreamReader(path); int iLnTmp = 0; //store the current line number while (!sr.EndOfStream) { iLnTmp++; string sTmp = sr.ReadLine(); //store the current line value if (sTmp.Contains("#Insert new information node below")) //insert PACS new node to config.cfg { sTmp += "\r\n" + sInsertText; //add new row of "sInsertText" } if (sTmp.Contains("this is the line for alias ")) { sTmp += ":" + alias; //append alias to "this is the line for alias " } sText += sTmp + "\r\n"; } sr.Close(); System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false); sw.Write(sText); sw.Flush(); sw.Close(); }
2.以下代码是在特定位置删除指定内容()
/// <summary> /// Delete information to txt file /// </summary> /// <param name="path">the path of txt file contains information you are going to delete</param> /// <param name="PacsNodeInfo">alias of information</param> private void DeleteInfoFromFile(string path, string information) { string alias = information.ToLower(); string sInsertText = alias + " = (" + information + ")"; string sText = ""; System.IO.StreamReader sr = new System.IO.StreamReader(path); int iLnTmp = 0; //store the current line number while (!sr.EndOfStream) { iLnTmp++; string sTmp = sr.ReadLine(); //store the current line value if (sTmp.Contains(sInsertText)) //delete PACS node from config.cfg { string lineAfterNode = sr.ReadLine(); sText += lineAfterNode + "\r\n"; continue; } if (sTmp.Contains("this is the line for alias ")) { string temp = ":" + alias; sTmp = sTmp.Replace(temp, " "); //replace the certain content by space(delete it) } sText += sTmp + "\r\n"; } sr.Close(); System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false); sw.Write(sText); sw.Flush(); sw.Close(); }
浙公网安备 33010602011771号