Logan Young
Logan Young

Reputation: 431

How to delete the first and last lines from a text file in visual basic

I've seen posts on deleting the lines from a text file that are specified as a function parameter, but I only need to delete the first and last lines from the file.

I'm still a newbie when it comes to working in files, but it seems that it should be simple to delete the first line... Just delete all text from BOF to the first CrLf character. Am I right?

As for the last line, I understand that I'll have to get a count of the lines in the text file to find it (as the file won't always be x amount of lines long). This is where I really need some help.

N.B. I'm using VB.NET 2005

Upvotes: 3

Views: 23590

Answers (3)

dbasnett
dbasnett

Reputation: 11773

This is to delete the last line, without reading the entire file. You may need to modify the logic to account for the EOF being a newline...

    Dim fs As New FileStream("c:\test.txt", FileMode.Open, FileAccess.ReadWrite)
    Dim b(1) As Byte

    Do
        fs.Seek(fs.Length - 2, SeekOrigin.Begin) 'seek 2 bytes from EOF
        fs.Read(b, 0, 2) 'read last two bytes
        'are they newline
        If System.Text.Encoding.ASCII.GetString(b, 0, 2) <> Environment.NewLine Then
            fs.SetLength(fs.Length - 1) 'set length to -1
        Else
            fs.SetLength(fs.Length - 2)
            Exit Do
        End If
    Loop
    fs.Close()

Upvotes: 1

Joel Etherton
Joel Etherton

Reputation: 37533

Read the file in to a list of lines as string completely. Write the file back out using an indexed loop to capture all but the first and last items.

    Dim listText As New List(Of String)
    Dim objLine As String = ""

    Using objReader As StreamReader = New StreamReader("c:\test.txt")
        Do
            objLine = objReader.ReadLine()
            If objLine IsNot Nothing Then listText.Add(objLine)
        Loop Until objLine Is Nothing
    End Using

    Using objWriter As StreamWriter = New StreamWriter("c:\testOutput.txt")
        For I As Integer = 1 To listText.Count - 2
            objWriter.WriteLine(listText.Item(I))
        Next
    End Using

Edit to satisfy the very picky:

    Dim arrText() As String
    Dim sLine As String = ""

    arrText = File.ReadAllLines("c:\test.txt")

    Using objWriter As StreamWriter = New StreamWriter("c:\testOutput.txt")
        For I As Integer = 1 To arrText.Length - 2
            objWriter.WriteLine(arrText(I))
        Next
    End Using

Upvotes: 4

Hans Passant
Hans Passant

Reputation: 941465

Files are streams, there are no shortcuts. You have to read the entire file and write it back, minus the first and last line. Horribly inefficient of course, use a database instead.

Upvotes: 0

Related Questions