问题描述
我正在尝试在文件中添加特定的文本行.特别是在两个边界之间.
I am trying to add a specific line of text in a file. Specifically between two boundaries.
如果我想在 item1 的边界之间添加一条线会是什么样子的示例:
An example of what it would look like if I wanted to add a line in between the boundaries of 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]
这是我迄今为止尝试过的,但它远非正确.它一直说该文件正在被读者使用,因此作者无法对其进行编辑,当我让它工作时,它清除了整个文档.
This is what I have tried so far, however Its nowhere near correct. It keeps saying that the file is being used by the reader so it cant be edited by the writer, when I did get it to work it cleared the entire document.
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");
}
}
我也想知道如何在文档末尾写行.
I would also like to know how to write lines at the end of the document.
推荐答案
这将添加您想要的行.(确保你有 using System.IO;
和 using System.Linq;
添加)
This will add the line where you want it. (Make sure you have using System.IO;
and using System.Linq;
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.
}
这篇关于在文本文件中的特定位置添加新行.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!