Open a file - replace 1 word - close a file

In my under - sized brain this code should work.

 If File.Exists("C:\KeyPatroller\SQL\CorporateRemote.sql") Then

            fStream = New FileStream("C:\KeyPatroller\SQL\CorporateRemote.sql", FileMode.Open, FileAccess.ReadWrite)

            sReader = New StreamReader(fStream)

            sReader.ReadToEnd.Replace("keypatrollerremote", "Bob")


        End If
Who is Participating?
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
This line:

    sReader.ReadToEnd.Replace("keypatrollerremote", "Bob")

Creates a string with the word replaced...but that string is not "linked" to your file at all.  The string is simply garbage collected when the sub/function exits.

You need to store that modified string and then OVERWRITE the old file:
Dim FileName As String = "C:\KeyPatroller\SQL\CorporateRemote.sql"
        If File.Exists(FileName) Then
            Dim contents As String = My.Computer.FileSystem.ReadAllText(FileName)
            contents = contents.Replace("keypatrollerremote", "Bob")
            My.Computer.FileSystem.WriteAllText(FileName, contents, False)
        End If

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.