且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在一个文本文件中的特定位置添加一个新行。

更新时间:2023-11-30 08:51:22

这将增加您想要的位置就行了。 (请确保您有使用System.IO; 添加)

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

public void createEntry(String npcName)
{
    //npcName = @"[/item1]"; <-- note the '/'.
    string lineToAdd = "//Add a line here in between the specific boundaries";
    string fileName = "test.txt";
    List<string> txtLines = new List<string>();

    //Fill a List<string> with the lines from the txt file.
    foreach (string str in File.ReadAllLines(fileName))
    {
        txtLines.Add(str);
    }

    //Insert the line you want to add last under the tag 'item1'.
    txtLines.Insert(txtLines.IndexOf(npcName), lineToAdd);

    //Clear the file. The using block will close the connection immediately.
    using (File.Create(fileName)) { }

    //Add the lines including the new one.
    foreach (string str in txtLines)
    {
        File.AppendAllText(fileName, str + Environment.NewLine);
    }
}






两年UPDATE:这是我最高的投票答案,但我两年前写的,它可以使用一些改进。我正在做一些奇怪的东西,在上​​面的方法,我想为未来的读者一个更好的选择。


TWO YEAR UPDATE: This is my highest voted answer but I wrote it two years ago and it could use some improvements. I'm doing some strange things in the above method and I want to provide a better alternative for future readers.

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.
}