Add a new line at a specific position in a text file.

后端 未结 3 1638
感情败类
感情败类 2020-12-02 00:16

I am trying to add a specific line of text in a file. Specifically between two boundaries.

An example of what it would look like if I wanted to add a line in between

3条回答
  •  爱一瞬间的悲伤
    2020-12-02 00:28

    This will add the line where you want it. (Make sure you have using System.IO; and using System.Linq; added)

    public void CreateEntry(string npcName) //npcName = "item1"
    {
        var fileName = "test.txt";
        var endTag = String.Format("[/{0}]", npcName);
        var lineToAdd = "//Add a line here in between the specific boundaries";
    
        var txtLines = File.ReadAllLines(fileName).ToList();   //Fill a list with the lines from the txt file.
        txtLines.Insert(txtLines.IndexOf(endTag), lineToAdd);  //Insert the line you want to add last under the tag 'item1'.
        File.WriteAllLines(fileName, txtLines);                //Add the lines including the new one.
    }
    

提交回复
热议问题