简体   繁体   English

使用VB.Net读取和写入文本文件中的特定行

[英]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 所以这是我的问题:第一,我需要阅读一个文本文件并获得第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" 所以,我需要的是替换值200,比方说250并保持这样的行: 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. 如果您的文本文件被划分为行,并且您只想查看第5行,则可以使用ReadAllLines将行读取为String数组。 Process line 4 (the 5th line) and use WriteAllLines to re-write the file. 处理第4行(第5行)并使用WriteAllLines重写文件。 The following example checks that the file contains at least 5 lines and that the 5th line begins with "ORIGIN "; 以下示例检查文件是否包含至少5行,第5行以“ORIGIN”开头; if so it replaces the line with ORIGIN "250" and re-writes the file. 如果是这样,它用ORIGIN“250”替换该行并重新写入该文件。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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