【问题标题】:Add a new line at a specific position in a text file.在文本文件的特定位置添加新行。
【发布时间】:2023-08-07 05:34:01
【问题描述】:

我正在尝试在文件中添加特定的文本行。特别是在两个边界之间。

如果我想在 item1 的边界之间添加一条线会是什么样子的示例:

[item1]
2550 coins 995 200000 7
2550 coins 995 200000 7
2550 coins 995 200000 7
2550 coins 995 200000 7
2550 coins 995 200000 7
//Add a line here in between the specific boundaries
[/item1]
[item2]
2550 coins 995 200000 7
2550 coins 995 200000 7
2550 coins 995 200000 8
2550 coins 995 200000 7
2550 coins 995 200000 7
[/item2]
[item3]
2550 coins 995 200000 7
2550 coins 995 200000 7
2550 coins 995 200000 7
2550 coins 995 200000 7
2550 coins 995 200000 7
[/item3]

这是我迄今为止尝试过的,但它远非正确。它一直说该文件正在被阅读器使用,因此作者无法编辑它,当我让它工作时它清除了整个文档。

public void createEntry(String npcName)
{
    String line;
    String fileName = "Drops.de";
    StreamWriter streamWriter = new StreamWriter(fileName);
    StreamReader streamReader = new StreamReader(fileName);
    line = streamReader.ReadLine();
    if (line == ("[" + npcName + "]"))
    {
        streamReader.ReadLine();
        streamWriter.WriteLine("Test");
    }
}

我也想知道如何在文档末尾写行。

【问题讨论】:

  • 像上一个问题一样读取文件,并在添加新行的同时写入新文件。
  • 我添加了我尝试过的,我认为到目前为止还很遥远

标签: c# io streamwriter


【解决方案1】:

这会将行添加到您想要的位置。 (确保您添加了using System.IO;using System.Linq;

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

【讨论】:

  • 谢谢你,唯一的问题是它一直告诉我文件正在使用中,在“使用 (File.Create(fileName)){}”
  • 奇怪,它对我来说很好用。您还有其他使用该文件的代码吗?您不需要任何 FileStreamStreamWriterStreamReader 即可。
  • 啊,对不起。我的其他方法之一正在影响您的方法。无论如何,目前它似乎工作得很好,谢谢:)
  • 很高兴你能成功。我希望这也涵盖了您的第二个问题,您也可以使用此代码在末尾添加一行。
  • 我不建议使用该代码将文本附加到末尾。因为它必须将整个文件完全加载到内存中。相反,我建议:使用 var fileSteam = File.AppendText(path); .fileSteam.WriteLine(newItem);
【解决方案2】:

你不应该打开你的文件两次,试试这个:

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

另一个想法是插入行的逻辑,也许更简单的方法是将数据逐行复制到新文件中,在需要时插入新部分并继续。或者在记忆中做。

要将行添加到末尾,您可以使用 FileMode.Append 或自行查找

【讨论】:

    【解决方案3】:

    试试这个方法

    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);
            }
        }
    

    【讨论】:

      最近更新 更多