有没有一个函数可以编辑文本文件vb.net中的特定行



我试图编辑文本文件中的一行,因为我知道该文件包含数千行。有人能帮忙吗?我试过这个,但没有成功

Dim file As New StreamWriter("prds.dt")
file.write("text")
file.close

如何更改文件的X行:


Imports System.IO
...
Private Sub ChangeLine(ByVal path as String, ByVal lineNumber as Integer, ByVal newContent As String
Dim lines() as String = File.ReadAllLines(path)
lines(lineNumber - 1) = newContent 'arrays run from 0; line X of the file is in array slot X - 1
File.WriteAllLines(path, lines) 'simple version, or choose a version that uses particular encoding
End Sub

注意这里没有检查;如果文件的行数至少没有,则会出现崩溃。Robusting this up is a task for the user of this code

如何更改文件中所有表示X的行,使其表示Y:


Imports System.IO
...
Private Sub FindReplaceInFile(ByVal path as String, ByVal findString as String, ByVal replaceWith As String
Dim lines() as String = File.ReadAllLines(path)
For i as Integer = 0 to lines.Length - 1
lines(i) = lines(i).Replace(findStr, replaceWith) 'case sensitive!
Next i
File.WriteAllLines(path, lines) 'simple version, or choose a version that uses particular encoding
End Sub

最新更新