none
Replacing text in a text file. RRS feed

  • Question

  • Hi everyone,

    I am trying to use the .Replace command to replace (obviously) one line of text in a text file with another. I believe I am doing it wrong by using sr.Readline.Replace() because nothing happens when the button is clicked. I have checked the rest of my code and debugged it using a different Then statement.

    If anyone has any solutions/suggestions it would be greatly appreciated!

    Imports System
    Imports System.IO
    Public Class Form1
        Dim Oldname As String
        Dim Newname As String
        Dim file_location As String = "C:\Users\Jared\source\repos\Replace\Replace\bin\customers.txt.txt"
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Oldname = txtOldname.Text
            Newname = txtNewname.Text
            Using sr As StreamReader = File.OpenText(file_location)
                Do Until sr.Peek = -1
                    If Oldname.Contains(sr.ReadLine) Then
                        sr.ReadLine.Replace((Oldname), (Newname))
                    End If
                Loop
            End Using
    
        End Sub
    
    
    ....
    
    
    
    
    
    
    End Class

    Sunday, November 26, 2017 12:50 AM

All replies

  • js,

    I haven't tested this, but it should be close:

        Private Sub _
            FindAndReplace(ByVal textFilePath As String, _
                           ByVal findText As String, _
                           ByVal replaceText As String)
    
            If Not String.IsNullOrWhiteSpace(textFilePath) Then
                Dim fi As New IO.FileInfo(textFilePath)
    
                If fi.Exists Then
                    If Not String.IsNullOrWhiteSpace(findText) AndAlso _
                        Not String.IsNullOrWhiteSpace(replaceText) Then
    
                        Dim sb As New System.Text.StringBuilder
                        sb.Append(IO.File.ReadAllText(fi.FullName))
    
                        sb.Replace(findText, replaceText)
    
                        fi.Delete()
    
                        IO.File.WriteAllText(fi.FullName, sb.ToString)
                    End If
                End If
            End If
    
        End Sub


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, November 26, 2017 1:06 AM
  • Hi everyone,

    I am trying to use the .Replace command to replace (obviously) one line of text in a text file with another. I believe I am doing it wrong by using sr.Readline.Replace() because nothing happens when the button is clicked. I have checked the rest of my code and debugged it using a different Then statement.

    If anyone has any solutions/suggestions it would be greatly appreciated!

    Imports System
    Imports System.IO
    Public Class Form1
        Dim Oldname As String
        Dim Newname As String
        Dim file_location As String = "C:\Users\Jared\source\repos\Replace\Replace\bin\customers.txt.txt"
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Oldname = txtOldname.Text
            Newname = txtNewname.Text
            Using sr As StreamReader = File.OpenText(file_location)
                Do Until sr.Peek = -1
                    If Oldname.Contains(sr.ReadLine) Then
                        sr.ReadLine.Replace((Oldname), (Newname))
                    End If
                Loop
            End Using
    
        End Sub
    
    
    ....
    
    
    
    
    
    
    End Class

    Hi

    What about your other thread which already provided an answer!  HERE


    Regards Les, Livingston, Scotland

    Sunday, November 26, 2017 1:32 AM
  • Both Frank and Leshay have provided good points and code samples to work with and would suggest selecting one and teak to suit your needs, if you get stuck then come back and tell us what is going on.

    Now if you had a very large file here is a method that would work but I stress working with what I mentioned above as the following is way overkill for small files.

    Class with method to read, search/replace

    Imports System.IO
    
    Public Class FileOperations
        Private mHasException As Boolean
        Public ReadOnly Property HasException As Boolean
            Get
                Return mHasException
            End Get
        End Property
        Private mException As Exception
        Public ReadOnly Property LastException As Exception
            Get
                Return mException
            End Get
        End Property
        ''' <summary>
        ''' This method is overkill for small files, 
        ''' the intent is to work on very large files.
        ''' </summary>
        ''' <param name="pOriginalFile">File to read</param>
        ''' <param name="pOutputFile">Write results too</param>
        ''' <param name="pSearchTerm">Search for</param>
        ''' <param name="pReplaceTerm">Replace pSearchTerm</param>
        ''' <returns></returns>
        ''' <remarks>Could/Should be asynchronous either within the method or 
        ''' caller wraps this method in a Task.Run via await</remarks>
        Public Function ReplaceTextInFile(
            ByVal pOriginalFile As String,
            ByVal pOutputFile As String,
            ByVal pSearchTerm As String,
            ByVal pReplaceTerm As String) As Boolean
    
            mHasException = False
    
            Try
                Dim tempLineValue As String
                Using inputStream As FileStream = File.OpenRead(pOriginalFile)
                    Using inputReader As New StreamReader(inputStream)
                        Using outputWriter As StreamWriter = File.AppendText(pOutputFile)
                            tempLineValue = inputReader.ReadLine()
                            Do While Nothing IsNot tempLineValue
                                outputWriter.WriteLine(tempLineValue.Replace(pSearchTerm, pReplaceTerm))
                                tempLineValue = inputReader.ReadLine()
                            Loop
                        End Using
                    End Using
                End Using
                File.Delete(pOriginalFile)
                File.Move(pOutputFile, pOriginalFile)
                mHasException = False
            Catch ex As Exception
    
                mHasException = True
                mException = ex
    
            End Try
    
            Return Not mHasException
    
        End Function
    
    End Class
    

    Implement in a form

    Imports System.IO
    
    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim readFile As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TextFile1.txt")
            Dim outFile As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TextFile2.txt")
            Dim ops As FileOperations = New FileOperations()
            If ops.ReplaceTextInFile(readFile, outFile, "Karen", "Mary") Then
                MessageBox.Show("Done")
            Else
                Dim Message As String = "Failed to complete operation"
                If ops.HasException Then
                    Message = String.Concat(Message, Environment.NewLine, ops.LastException.Message)
                End If
                MessageBox.Show(Message)
            End If
        End Sub
    End Class
    
    Note, the reason for placing the code into a class is that we can re-use it in other forms and other projects as it has zero attachments in a project.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Sunday, November 26, 2017 3:03 AM
    Moderator
  • I am trying to use the .Replace command to replace (obviously) one line of text in a text file with another. I believe I am doing it wrong by using sr.Readline.Replace() because nothing happens when the button is clicked.

    Please see the description for the Replace method:

    https://msdn.microsoft.com/en-us/library/fk49wtc1(v=vs.110).aspx

    It is a function that returns a value (a String).  You need to assign that return value to a variable, or display it in a text box or write it to a file or something.  Currently, it is being discarded.  Assigning it to a variable will make the code easy to debug.

    Sunday, November 26, 2017 3:05 AM
  • Hi js1307,

    You can try the following code:

     Dim path As String = "D:\test\Text Document.txt"
            Dim findtext As String = "Search Text"
            Dim replacetext As String = "Replace Text"
            Dim objreader As New StreamReader(path)
            Dim content As String = objreader.ReadToEnd()
            objreader.Close()
            content = Regex.Replace(content, findtext, replacetext)
            Dim writer As New StreamWriter(path)
            writer.Write(content)
            writer.Close()
            MessageBox.Show("Replace successfully!")

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, November 27, 2017 6:43 AM
    Moderator