简体   繁体   中英

Read and Write to specific line in textfile with VB.Net

So here is my problem: 1st I need to read a text file and get the line number 5

System.IO.File.ReadAllText("E:\myFile.txt")

My text file its something like this:

ABCDE "2015"
GDFTHRE "0.25 0.25"
TRYIP "192.168.1.6"
WIDTH "69222"
ORIGIN "200"

So, what i need is to replace the value 200, lets say 250 and keep the line as this: ORIGIN "250"

I have tryed with the Replace but i can't get it.

If your text file is divided into lines and you only want to look at the 5th line, you can use ReadAllLines to read the lines into an array of String. Process line 4 (the 5th line) and use WriteAllLines to re-write the file. The following example checks that the file contains at least 5 lines and that the 5th line begins with "ORIGIN "; if so it replaces the line with ORIGIN "250" and re-writes the file.

Dim filePath As String = "E:\myFile.txt"
Dim lines() As String = System.IO.File.ReadAllLines(filePath)
If lines.Length > 4 AndAlso lines(4).StartsWith("ORIGIN ") Then
    lines(4) = "ORIGIN ""250"""
    System.IO.File.WriteAllLines(filePath, lines)
End If

You can simply replace the text and then write everything back to the file again:

Dim content As String

' read all text from the file to the content variable
content = System.IO.File.ReadAllText("E:\myFile.txt")

' replace number, text, etc. in code
content = content.Replace("<string to replace>","<replace with>")

' write new text back to the file (by completely overwriting the old content)
System.IO.File.WriteAllText("E:\myFile.txt",content)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM