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

我想在文件中添加特定的文本行。 具体在两个边界之间。

如果我想在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"); } } 

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

这将添加您想要的行。 (确保您using System.IO;添加)

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

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

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

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

要在最后添加行,您可以使用FileMode.Append或进行自己的搜索

试试这个方法

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