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



例如,我想修改文本文件中只写在[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返回文本文件中的行数组。获取包含搜索文本的行的索引。然后得到TextBox1中的行数组。只需将新文本分配给文件中行中适当的索引。最后,我显示了新的字符串TextBox2

确保两个文本框都足够宽以显示行,并且Multiline = True

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FileLines = File.ReadAllLines("C:DesktopCodeDemoMessage.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

最新更新