Sim*_*lor 11 c# io streamwriter
我想在文件中添加特定的文本行.具体在两个边界之间.
如果我想在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]
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止所尝试过的,但它远不是正确的.它一直说文件正在被读者使用,所以它不能被作者编辑,当我确实让它工作时它清除了整个文件.
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");
}
}
Run Code Online (Sandbox Code Playgroud)
我还想知道如何在文档末尾写行.
Hja*_*r Z 17
这将添加您想要的行.(确保你已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.
}
Run Code Online (Sandbox Code Playgroud)