如何使用vb.net在文本文件的指定行之后(或之前)添加文本?
提前致谢
答案 0 :(得分:0)
要将第5行之后的文本添加到文本文件中,只需调用:
AppendAtPosition("C:\Temp\test.txt", 5, "contenttoappend")
要将第5行之前的文本添加到文本文件中,只需调用
AppendAtPosition("C:\Temp\test.txt", 4, "contenttoappend")
需要此功能:
如果文本文件的行数少于预期,则将在最后一行之后添加内容。
Private Sub AppendAtPosition(ByVal ltFilePath As String, ByVal liAppendLine As Integer, ByVal ltAppendLine As String)
Dim ltFileContents As String = ""
Dim lReader As StreamReader = New StreamReader(ltFilePath)
Dim liRow As Integer = 0
While Not lReader.EndOfStream
ltFileContents &= lReader.ReadLine
If liRow = liAppendLine Then
ltFileContents &= ltAppendLine
Exit While
End If
liRow += 1
End While
If liAppendLine >= liRow Then
ltFileContents &= ltAppendLine
End If
File.WriteAllText(ltFilePath, ltFileContents)
End Sub