【问题标题】:search replace does nothing搜索替换什么都不做
【发布时间】:2013-04-18 10:48:38
【问题描述】:

我正在尝试编辑文件夹 (textbox4) 中的所有 txt 文件。如果它找到搜索的单词 (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

【问题讨论】:

  • 这不是 StackOverflow 的工作方式。首先你必须表现出一些努力和到目前为止you have tried 的内容,然后我们会尽力帮助你。

标签: .net vb.net io replace


【解决方案1】:

string.Replace() 返回新值而不是修改现有实例。如果需要,您需要存储结果:

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

【讨论】:

    【解决方案2】:

    试试这个:

    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
    

    到 [Find] 、 [Replace] 和 [Path] 是 textbox.text 的地方

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-01
      • 2012-11-20
      • 2018-12-02
      • 1970-01-01
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      相关资源
      最近更新 更多