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

后端 未结 3 1637
感情败类
感情败类 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:41

    try this method

    using System.IO;
    using System.Linq;
    
        /// 
        /// Add a new line at a specific position in a simple file        
        /// 
        /// Complete file path
        /// Line to search in the file (first occurrence)
        /// Line to be added
        /// insert above(false) or below(true) of the search line. Default: above 
        internal static void insertLineToSimpleFile(string fileName, string lineToSearch, string lineToAdd, bool aboveBelow = false)
        {          
            var txtLines = File.ReadAllLines(fileName).ToList();
            int index = aboveBelow?txtLines.IndexOf(lineToSearch)+1: txtLines.IndexOf(lineToSearch);
            if (index > 0)
            {
                txtLines.Insert(index, lineToAdd);
                File.WriteAllLines(fileName, txtLines);
            }
        }
    

提交回复
热议问题