2015-02-10 200 views
1

因此,这里是我的问题: 1我需要阅读的文本文件,并得到行号5读取和写入特定行的文本文件与VB.Net

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

我的文本文件的是这样的:

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

所以,我需要的是替换值200,可以说250,并保持该行,这样的:ORIGIN "250"

我已经tryed与替换,但我不能得到它。

回答

2

如果您的文本文件被分为行和你只想看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 
1

你可以简单地替换文本,然后再写的一切回文件:

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) 
相关问题