vb.net向txt第三行追加内容
时间: 2023-08-01 21:15:25 浏览: 118
您可以按照以下步骤将内容追加到txt文件的第三行:
1. 首先,使用 System.IO 命名空间中的 StreamReader 类读取 txt 文件的内容。
2. 然后,使用 List<string> 类型的变量存储每一行的文本。
3. 接下来,使用 List<string> 的 Insert 方法在第三行后添加新的文本。
4. 最后,使用 StreamWriter 类将新的文本写回到 txt 文件中。
下面是一个示例代码:
```
Dim filePath As String = "C:\example.txt"
Dim newText As String = "This is the new text to be added."
' 读取 txt 文件内容
Dim lines As New List(Of String)
Using reader As New StreamReader(filePath)
While Not reader.EndOfStream
lines.Add(reader.ReadLine())
End While
End Using
' 在第三行后添加新的文本
lines.Insert(2, newText)
' 将新的文本写回到 txt 文件中
Using writer As New StreamWriter(filePath)
For Each line As String In lines
writer.WriteLine(line)
Next
End Using
```
注意:这个例子中假设 txt 文件至少有三行。如果 txt 文件的行数少于三行,那么 Insert 方法可能会引发异常。
阅读全文
相关推荐


















