0

如何使用 vb.net 在文本文件的指定行之后(或之前)添加文本?
提前致谢

4

1 回答 1

0

要将第 5 行之后的文本添加到文本文件,只需调用:

AppendAtPosition("C:\Temp\test.txt", 5, "contenttoappend")

要将第 5 行之前的文本添加到 Textfile 只需调用

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
于 2013-04-09T11:55:23.883 回答