覆盖参数 [ 和 ] 之间的文本文件

Overwrite text file between parameters [ and ]

例如,我想在文本文件中仅修改我的文本框中 [newtext] 103 和 [endtext] 103 之间写入的内容。

[newtext]101
This is a first demonstration
This is a message
of Hello World
[endtext]101

[newtext]102
This is a 2nd demonstration
This is a 2nd message
of Hello World
[endtext]102

[newtext]103
This is a 3nd demonstration
This is a 3nd message
of Hello World
[endtext]103

所以如果我的文本框中有文本

This is a newest demonstration
This is a newest message
of Hello World

我如何适应用新文本替换文件旧文本?也就是说,输出将是: 注意,[newtext] 101, [newtext] 102之间的其他值不会被删除。

[newtext]103
This is a newest demonstration
This is a newest message
of Hello World
[endtext]103

这是一个代码,但不幸的是它必须找到所选参数之间的值。

Dim text As String = File.ReadAllText(My.Application.Info.DirectoryPath + ("\Data.txt"))
text = text.Replace(TextBox1.Text, TextBox2.Text)
File.WriteAllText("Data.txt", text)

ReadAllLines returns 文本文件中的行数组。获取包含搜索文本的行的索引。然后获取 TextBox1 中的行数组。只需将新文本分配给文件行中的适当索引即可。最后,我显示了新字符串 TextBox2.

确保两个文本框都足够宽以显示线条并且 Multiline = True。

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim FileLines = File.ReadAllLines("C:\Desktop\Code\DemoMessage.txt")
    Dim lineToFind = "[newtext]103"
    Dim index = Array.IndexOf(FileLines, lineToFind)
    Dim tbLines = TextBox1.Lines
    FileLines(index + 1) = tbLines(0)
    FileLines(index + 2) = tbLines(1)
    FileLines(index + 3) = tbLines(2)
    TextBox2.Text = String.Join(Environment.NewLine, FileLines)
    'you can write the contents of TextBox2 back to file if needed.
End Sub