Unless you know for a fact that the binary form of the text you're replacing is exactly the same length as the binary form of the text you're replacing it with (which would be a rare thing) you can't just edit a text file in place. You almost always have to read the whole lot in and then write the whole lot back out again. If it's a small file then the best option is to read the whole lot into memory, edit it, then write the whole lot out again, e.g.
Dim lines = File.ReadAllLines(filePath)
'Edit the second line.
lines(1) = "new text here"
File.WriteAllLines(filePath, lines)
Where ReadAllText reads the entire file contents into a single String, ReadAllLines reads the lines of the file into a String array.
If the file might be large then it's not a good idea to store the whole thing in memory at the same time. In that case, you can read the file line by line and write it out to a temp file, editing as you go. When you're done, you can move the temp file and overwrite the original file, e.g.
Dim tempFilePath = Path.GetTempFileName()
Using reader As New StreamReader(filePath),
writer As New StreamWriter(tempFilePath)
Dim lineIndex = 0
Do Until reader.EndOfStream
Dim line = reader.ReadLine()
If lineIndex = 1 Then
line = "new text here"
End If
writer.WriteLine(line)
lineIndex += 1
Loop
End Using
My.Computer.FileSystem.MoveFile(tempFilePath, filePath, True)
or, from .NET 4.0:
Dim tempFilePath = Path.GetTempFileName()
Using writer As New StreamWriter(tempFilePath)
Dim lineIndex = 0
For Each line In File.ReadLines(filePath)
If lineIndex = 1 Then
line = "new text here"
End If
writer.WriteLine(line)
lineIndex += 1
Next
End Using
My.Computer.FileSystem.MoveFile(tempFilePath, filePath, True)
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.