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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28436164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:47:15  来源:igfitidea点击:

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

vb.net

提问by Rob

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

所以这是我的问题:1st 我需要读取一个文本文件并获取第 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.

我已经尝试过替换,但我无法得到它。

回答by Blackwood

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.

如果你的文本文件被分成几行,而你只想看第5行,你可以使用ReadAllLines将这些行读入一个String数组。处理第 4 行(第 5 行)并使用 WriteAllLines 重新写入文件。以下示例检查文件是否至少包含 5 行,并且第 5 行是否以“ORIGIN”开头;如果是这样,它将用 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

回答by WeSt

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)