2015-02-10 199 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) 
相關問題