Search code examples
.netvb.netioreplace

search replace does nothing


I am trying to edit all txt files in a folder (textbox4). If it finds searched word (textbox2) it repleaces with other (textbox3). But code does nothing.

Dim mydir As String = TextBox4.Text
Dim savetxt As New List(Of String)
For Each txtfile As String In System.IO.Directory.GetFiles(mydir, "*.txt") 
For Each line As String In System.IO.File.ReadAllLines(txtfile)
If line.Contains(TextBox2.Text) Then
line.Replace(TextBox2.Text, TextBox3.Text)
End If
savetxt.Add(line)
Next
System.IO.File.WriteAllLines(txtfile, savetxt.ToArray)
savetxt.Clear()
Next

Solution

  • string.Replace() returns the new value rather than modifying the existing instance. You need to store the result if it's needed:

    line = line.Replace(TextBox2.Text, TextBox3.Text);