Delete specific lines in a text file using

19055 просмотра

3 ответа

I am trying to delete some specific lines of a text using VB.Net. I saw a solution here however it is in VB6. The problem is, I am not really familiar with VB6. Can somebody help me? This is the code from the link:

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
                bLineFound = True

            End If
            lCtr = lCtr + 1

        oFSTR = oFSO.CreateTextFile(fName, True)

        DeleteLine = bLineFound
    End If

    On Error Resume Next
    oFSTR = Nothing
    oFSO = Nothing

End Function
Автор: svynsaenz Источник Размещён: 13.11.2019 11:33

Ответы (3)

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)
Автор: David Sdot Размещён: 20.05.2014 09:06

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
            'don't add your line to txtbox
        End If
Автор: HuH Размещён: 20.05.2014 09:05

0 плюса

Or You Can Use

TextFile = TextFile.Replace("You want to Delete","")

Автор: GoroundoVipa Размещён: 20.05.2014 09:02
Вопросы из категории :