none
Replace a word in a text file.

    Question

  • Hi,
    how to create a code that will replace in a text file - ("c/test.txt")
    the word "google" to "yahoo".
    Sunday, January 06, 2008 12:23 AM

Answers

  • Code Block

    Dim S As String = IO.File.ReadAllText("C:\Test.txt")

    S.Replace("google", "yahoo")

    IO.File.WriteAllText("C:\Test.txt", S)

     

    Edit:

    Second line should be:

    Code Block

    S = S.Replace("google", "yahoo")

     

     

    Sunday, January 06, 2008 9:24 AM
  • This only works:


    Dim S As String = IO.File.ReadAllText("C:\Test.txt")

    Dim S2 As String = Replace(S, "google", "yahoo")

    IO.File.WriteAllText("C:\Test2.txt", S2)



    Saturday, January 19, 2008 7:11 PM

All replies

  • Code Block

    Dim S As String = IO.File.ReadAllText("C:\Test.txt")

    S.Replace("google", "yahoo")

    IO.File.WriteAllText("C:\Test.txt", S)

     

    Edit:

    Second line should be:

    Code Block

    S = S.Replace("google", "yahoo")

     

     

    Sunday, January 06, 2008 9:24 AM
  • I am having no luck replacing a string within a text file can you help me out?

    here is the code I am using

    'Replaces a string with a new string

    Dim s As String = My.Computer.FileSystem.ReadAllText("c:\test11.txt")

    Dim q, c As Integer

    Dim sToRepl As String

    Dim x As Integer

    Try

    ' theStreamreader.Close()

    For c = 0 To lstValues.Items.Count - 1

    sToRepl = lstValues.Items(c).ToString

    For q = 1 To (txtNumlines.Text) - 1

    My.Computer.FileSystem.WriteAllText("c:\test11", s.Replace(sToRepl, "gggg"), False)

    x = x + 1

    Next q

    Next c

    theStreamreader.Close()

    Catch ex As Exception

    MsgBox(ex.Message, MsgBoxStyle.Critical)

    End Try

     

     

    Saturday, January 19, 2008 6:21 PM
  • What problems are you having using the code in my post?

    Saturday, January 19, 2008 6:42 PM
  • This only works:


    Dim S As String = IO.File.ReadAllText("C:\Test.txt")

    Dim S2 As String = Replace(S, "google", "yahoo")

    IO.File.WriteAllText("C:\Test2.txt", S2)



    Saturday, January 19, 2008 7:11 PM
  • The code ran OK (no errors) but did not replace the text.

    Sunday, January 20, 2008 4:07 PM
  • Did you use the edited code?

    Sunday, January 20, 2008 4:40 PM
  • When I used this code

    Dim S As String = IO.File.ReadAllText("C:\Test.txt")

    Dim S2 As String = Replace(S, "google", "yahoo")

    IO.File.WriteAllText("C:\Test2.txt", S2)

     

    I got a error saying "Replace", ambigious, imports etc.

     

    Yes, John I use your edited code. Looks like should work - It is somethings on my end.

    Monday, January 21, 2008 12:41 PM
  • @ bwcalvin

    You need first to create test1.txt and test2.txt,

    after that code should work!

    All works Ok!
    Monday, January 21, 2008 7:36 PM