我正在尝试编辑文件夹中的所有txt文件(textbox4)。如果它找到搜索到的单词(textbox2),它会与其他单词(textbox3)一起使用。但代码什么也没做。
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
答案 0 :(得分:4)
string.Replace()
返回新值,而不是修改现有实例。如果需要,您需要存储结果:
line = line.Replace(TextBox2.Text, TextBox3.Text);
答案 1 :(得分:1)
试试这个:
Private Function GetFiles(Path As String) As String()
Dim Files() As String = IO.Directory.GetFiles(Path)
Return Files
End Function
Private Sub ProcessFiles(Files As String(), Find As String, Replace As String)
Dim txt As String
For Each file In Files
txt = IO.File.ReadAllText(file)
If txt.Contains(Find) = True Then
IO.File.WriteAllText(file, txt.Replace(Find, Replace))
End If
Next
End Sub
然后像这样实施:
Private Sub Initate(Path As String, Find As String, Replace As String)
'get the files paths
Dim files() As String = GetFiles(Path)
'find the text and replaces it
ProcessFiles(files, Find, Replace)
End Sub
到[查找],[替换]和[路径]是textbox.text
的位置