首页 > 解决方案 > 是否有一个功能可以编辑文本文件 vb.net 中的特定行

问题描述

我正在尝试编辑文本文件中的一行,知道该文件包含数千行。请问有什么机构可以帮忙吗?我试过这个但徒劳无功

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

标签: vb.nettext-files

解决方案


如何更改文件的 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

注意这里没有检查;如果文件至少没有行数,则会崩溃。加强这一点是此代码用户的任务

如何更改文件中所有说 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

推荐阅读