Frosty Tosty
Frosty Tosty

Reputation: 63

Replace a certain word/string in a .txt file with another word/string. VB.NET

Hmm so i think the title explains enough. Hope someone has a answer. Thanks... Pretty much all I need to do is replace a string from a text file with another one. Any ideas?

Upvotes: 1

Views: 3895

Answers (2)

Gianluca Colombo
Gianluca Colombo

Reputation: 819

What you need is the code below... sourced on stackoverflow

 Dim myStreamReaderL1 As System.IO.StreamReader
        Dim myStream As System.IO.StreamWriter

        Dim myStr As String
        myStreamReaderL1 = System.IO.File.OpenText("C:\File.txt")
        myStr = myStreamReaderL1.ReadToEnd()
        myStreamReaderL1.Close()


        myStr = myStr.Replace("OldString", "New String")
        'Save myStr
        myStream = System.IO.File.CreateText("C:\FileOut.txt")
        myStream.WriteLine(myStr)
        myStream.Close()

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460028

The easiest is to rewrite the whole file if it's not too large:

File.WriteAllText(path, File.ReadAllText(path).Replace(oldText, newText))

If you have to replace all words it's a little bit more difficult. Btw, what is a word by your definition at all? Here is one approach:

Dim newWords = From word In File.ReadAllText(path).Split()
               Select If(word = oldWord, newWord, word)
File.WriteAllText(path, String.Join(" ", newWords))

Upvotes: 1

Related Questions