Remove blank line(s) from text file

dsm1995gst

Member
Joined
Apr 29, 2011
Messages
16
Programming Experience
1-3
I know this is simple but for some reason I can't seem to get it.

Basically I've got a list of items in a text file, but sometimes a blank line gets inadvertently put in there, and I need to be able to delete that line (or change that line to a set value, either is fine).

Thanks for any help.
 
VB.NET:
    Sub Main()
        Dim sr As New System.IO.StreamReader("c:\test.txt")
        Dim line As String = sr.ReadLine
        Dim sw As New System.IO.StreamWriter("c:\test_withoutblanklines.txt")
        While Not line Is Nothing
            If Not line = "" Then
                sw.WriteLine(line)
            End If
            line = sr.ReadLine
        End While
    End Sub
 
That works properly - now it seems my issue is that the text file is fairly long and is taking some time to "re-write."

Is there a piece of code that doesn't involve re-writing a new text file, but instead simply changes a blank line to a set string value like "ERROR" or "BLANK" or something?
 
VB.NET:
Sub Main()
        Dim sr As New System.IO.StreamReader("c:\test.txt")
        Dim line As String = sr.ReadLine
        While Not line Is Nothing
            If Not line = "" Then
                'every line that is not blank will end up here
            Else
                'blank lines come here
            End If
            line = sr.ReadLine
        End While
    End Sub
 
Here's a little shorter way to remove blank lines:

VB.NET:
Dim sText As String = File.ReadAllText("C:\test.txt")
Dim sNewLines() As String = sText.Split(New Char() {ControlChars.Lf}, StringSplitOptions.RemoveEmptyEntries)
File.WriteAllLines("C:\test.txt", sNewLines)

And to replace:

VB.NET:
Dim sLines() As String = File.ReadAllLines("C:\test.txt")
For i = 0 To sLines.Length - 1
    If sLines(i) = "" Or sLines(i) = ControlChars.Lf Or sLines(i) = ControlChars.Cr _
    Or sLines(i) = ControlChars.CrLf Then sLines(i) = "BLANK"
Next
File.WriteAllLines("C:\text.txt", sLines))

I am sure there is a way to do the replacing without going through each line, I just don't know it :)

Hope this helps
-Josh
 
Wow guys thanks for the quick help.

For some reason I still couldn't get the code to delete the line to work exactly right. However, I've already got a removeDuplicates() function written in the project, so I was able to just use the code to replace the blank line with a value that is already in the file and let the removeDuplicates() function handle it from there.

Thanks again.
 
Last edited:
Back
Top