-5

フォルダー (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
4

2 に答える 2

4

string.Replace()既存のインスタンスを変更するのではなく、新しい値を返します。必要に応じて結果を保存する必要があります。

line = line.Replace(TextBox2.Text, TextBox3.Text);
于 2013-04-24T18:31:00.153 に答える
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

[Find] 、 [Replace] 、および [Path] が textbox.text の場所へ

于 2013-04-24T23:35:42.670 に答える