使用vb.net删除文本文件中的特定行

时间:2014-05-20 08:57:26

标签: vb.net

我正在尝试使用VB.Net删除文本的某些特定行。我看到了一个解决方案here但它在VB6中。问题是,我对VB6并不熟悉。有人能帮助我吗? 这是链接中的代码:

Public Function DeleteLine(ByVal fName As String, ByVal LineNumber As Long) _As Boolean
    'Purpose: Deletes a Line from a text file

    'Parameters: fName = FullPath to File
    '            LineNumber = LineToDelete

    'Returns:    True if Successful, false otherwise

    'Requires:   Reference to Microsoft Scripting Runtime

    'Example: DeleteLine("C:\Myfile.txt", 3)
    '           Deletes third line of Myfile.txt
    '______________________________________________________________


    Dim oFSO As New FileSystemObject
    Dim oFSTR As Scripting.TextStream
    Dim ret As Long
    Dim lCtr As Long
    Dim sTemp As String, sLine As String
    Dim bLineFound As Boolean

    On Error GoTo ErrorHandler
    If oFSO.FileExists(fName) Then
        oFSTR = oFSO.OpenTextFile(fName)
        lCtr = 1
        Do While Not oFSTR.AtEndOfStream
            sLine = oFSTR.ReadLine
            If lCtr <> LineNumber Then
                sTemp = sTemp & sLine & vbCrLf
            Else
                bLineFound = True

            End If
            lCtr = lCtr + 1
        Loop

        oFSTR.Close()
        oFSTR = oFSO.CreateTextFile(fName, True)
        oFSTR.Write(sTemp)

        DeleteLine = bLineFound
    End If


ErrorHandler:
    On Error Resume Next
    oFSTR.Close()
    oFSTR = Nothing
    oFSO = Nothing

End Function

3 个答案:

答案 0 :(得分:6)

Dim delLine As Integer = 10
Dim lines As List(Of String) = System.IO.File.ReadAllLines("infile.txt").ToList
lines.RemoveAt(delLine - 1) ' index starts at 0 
System.IO.File.WriteAllLines("outfile.txt", lines)

答案 1 :(得分:2)

    'This can also be the file that you read in
    Dim str As String = "sdfkvjdfkjv" & vbCrLf & "dfsgkjhdfj" & vbCrLf & "dfkjbhhjsdbvcsdhjbvdhs" & vbCrLf & "dfksbvashjcvhjbc"

    Dim str2() As String = str.Split(vbCrLf)

    For Each s In str2
        If s.Contains("YourString") Then
            'add your line to txtbox
        Else
            'don't add your line to txtbox
        End If
    Next

答案 2 :(得分:0)

或者你可以使用

TextFile = TextFile.Replace(“你想删除”,“”)