Reputation: 63
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
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
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