Frozen Blade Frozen Blade - 1 year ago 70 Question

VB.NET Multiple Replace In Text File

I have 2 files , one index.html which is more like a template , and output index file which is a new file. the first index file contains ##1 , ##2 .... ##24 inside it , and i want those to be replaced with some links i provide within a text file.

Let me explain my code. First i create my output file.
i declare the line array containing links which will replace the ##1 .... ##24.
i loop 24 times to replace all ## with the Links provided from allLines. In the final file it only replaces some of the ## and not all

My form looks like this

The problem is that it doesnt replace all links , it replaces only some of them and this is really weird.


Dim allLines As String() = System.IO.File.ReadAllLines(TextBox1.Text)
For c As Integer = 1 To 24 Step 1

My.Computer.FileSystem.WriteAllText(TextBox3.Text, My.Computer.FileSystem.ReadAllText(TextBox2.Text).Replace("##" & c, allLines(c - 1)), True)


Answer Source

The problem is that you are continuously reading/writing the file using the same source file (TextBox2.Text). File.WriteAllText overwrites any file that already exists and you aren't re-reading the contents of that file before doing the replace.

What you should do is read the text once, do all the replacements and then write the text out once. Something along these lines:

Dim sb as new StringBuilder(File.ReadAllText(TextBox2.Text))
Dim allLines = File.ReadAllLines(TextBox1.Text)
For c as Integer = 1 to 24
    sb.Replace("##"&c, allLines(c-1))
Next x

File.WriteAllText(TextBox3.Text, sb.ToString())

Note that you really need some error handling in there as well (to make sure there is data in those text boxes--which could also use better names)

You also don't need the call to File.Create(). File.WriteAllText will create the file if it does not exist .