George Vaisey
George Vaisey

Reputation: 149

Search/Replace in VB.NET

Been following the threads for sometime as a novice (more of a newbie) but am now starting to do more.

I can read how to open a text file but am having trouble understanding the .replace functionality (I get the syntax just can't get it to work).

Scenario:

Inputfile name = test_in.txt

replace {inputfile} with c:\temp\test1.txt

I'm using test.txt as a template for a scripting tool and need to replace various values within to a new file called test_2.txt.

I've got variables defining the input and output files without a problem, I just can't catch the syntax for opening the new file and replacing.

Upvotes: 2

Views: 583

Answers (2)

SysDragon
SysDragon

Reputation: 9888

Try something like this:

Dim sValuesToReplace() As String = New String() {"Value1", "Value2", "Value3"}
Dim sText As String = IO.File.ReadAllText(inputFilePath)

For Each elem As String In sValuesToReplace
    sText = sText.Replace(elem, sNewValue)
Next

IO.File.WriteAllText(sOutputFilePath, sText)

It depends if you want to replace all values with only one value, or with different values for each. If you need different values you can use a Dictionary:

Dim sValuesToReplace As New Dictionary(Of String, String)()

sValuesToReplace.Add("oldValue1", "newValue1")
sValuesToReplace.Add("oldValue2", "newValue2")
'etc

And then loop throgh it with:

For Each oldElem As String In sValuesToReplace.Keys
    sText = sText.Replace(oldElem, sValuesToReplace(oldElem))
Next

Upvotes: 1

Mark Hall
Mark Hall

Reputation: 54532

You really have not given us that much to go on. But a common mistake in using String.Replace is that it makes a copy of the source which needs to be saved to another variable or else it will go into the bit bucket. So in your case, something like this should work.

Dim Buffer As String 'buffer
Dim inputFile As String = "C:\temp\test.txt" 'template file
Dim outputFile As String = "C:\temp\test_2.txt" 'output file

Using tr As TextReader = File.OpenText(inputFile)
    Buffer = tr.ReadToEnd
End Using
Buffer = Buffer.Replace("templateString", "Hello World")

File.WriteAllText(outputFile, Buffer)

Upvotes: 2

Related Questions