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

允我心安 提交于 2019-11-27 09:27:03

This will add the line where you want it. (Make sure you have using System.IO; 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.
}

You should not open your file twice, try this:

FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
StreamWriter streamWriter = new StreamWriter(fileStream);
StreamReader streamReader = new StreamReader(fileStream);

another think is logic for inserting line, maybe easier way is to copy data line by line into new file, insert new part when needed and continue. Or do it in memory.

To add line to the end you can use FileMode.Append or do your own seek

try this method

using System.IO;
using System.Linq;

    /// <summary>
    /// Add a new line at a specific position in a simple file        
    /// </summary>
    /// <param name="fileName">Complete file path</param>
    /// <param name="lineToSearch">Line to search in the file (first occurrence)</param>
    /// <param name="lineToAdd">Line to be added</param>
    /// <param name="aboveBelow">insert above(false) or below(true) of the search line. Default: above </param>
    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);
        }
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!