I would like for example to modify in the text file only what is written between [newtext] 103 and [endtext] 103 , from my textbox.
[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
so if I have text in my textbox
This is a newest demonstration
This is a newest message
of Hello World
how do I adapt to replace file the old text with the new text? that is, the output will be:
attention, the other values between [newtext] 101, [newtext] 102
, will not be erase.
[newtext]103
This is a newest demonstration
This is a newest message
of Hello World
[endtext]103
this is a code, but unfortunately it has to find the values between the chosen parameters.
Dim text As String = File.ReadAllText(My.Application.Info.DirectoryPath ("\Data.txt"))
text = text.Replace(TextBox1.Text, TextBox2.Text)
File.WriteAllText("Data.txt", text)
CodePudding user response:
ReadAllLines
returns an array of the lines in the text file. The get the index of the line with the search text. Then get an array of the lines in the TextBox1
. Simply assign the new text to the proper indexes in the lines in the file. Lastly, I displayed the new string TextBox2
.
Be sure that both text boxes are wide enough to display the lines and have 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