ShaneRibz
ShaneRibz

Reputation: 107

How do I remove blank lines from text File? vb.net?

I have a program I am creating and when i go to remove blank lines this is how I go about it.

For Each i As ListViewItem In lvSongs.SelectedItems
        lvSongs.Items.Remove(i)
        CurrentSong = i.SubItems(4).Text 'This is the Songs Path

        files = File.ReadAllText("songs.txt") 'The songs path's are in the txt


        'I am using this as a list of lines i want to keep in
        'the txt file.
        Dim linesToKeep As New List(Of String)

        For Each line As String In files 'Goes through lines
            If Not line.Contains(CurrentSong) Then  'checks to see if line is Current song
                linesToKeep.Add(line)               'Adds line if its not CurrentSong to the list
            End If
        Next


        File.WriteAllLines("songs.txt", linesToKeep.ToArray())

but when i go to check the txt document, i get this:

EXAMPLE (but written horizontally, each letter being on a new line)

in the text file my friend says its because i have lines set as a string instead of a string().

Thanks for anyhelp! Ask for more information if im confusing you...

Upvotes: 0

Views: 3813

Answers (1)

JaredPar
JaredPar

Reputation: 754515

The problem is you are using the ReadAllText API. This returns a String not a String() hence when you later iterate you are iterating over every character in the file, not every line. To fix this use the ReadAllLines API which returns a String()

files = File.ReadAllLines("songs.txt")

Note I can't tell if files is an implicitly declared local or a field. If it's a field typed to String you will need to change the type to String().

Upvotes: 2

Related Questions