VB.NET remove extra blank lines from file


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 5 of 5

Thread: VB.NET remove extra blank lines from file

  1. #1
    Join Date
    Jul 2005
    Posts
    5

    VB.NET remove extra blank lines from file

    Hello,

    I have a file with multiple blank lines in it and I am trying to remove all extra blank lines. Single blank lines need to be preserved but anything more than one needs to be removed so the resulting output is just one blank line between output.

    example in:
    1

    2


    3



    4

    example out:
    1

    2

    3

    4


    The code I have removes all blank lines.
    1
    2
    3
    4

    <code>

    Imports System
    Imports System.IO
    Imports System.Collections
    Imports System.Text
    Imports Microsoft.VisualBasic

    Module Module1
    Sub Main()

    ' Create an empty string array to return to caller.
    Dim lines() As String = {}

    ' Check to see if the file exists.
    If IO.File.Exists("C:\test.txt") Then

    ' Open a stream reader to get the text from the file.
    Dim sr As New IO.StreamReader("C:\test.txt")

    ' Read all the file text.
    Dim fileText As String = sr.ReadToEnd()

    ' Split the text into a string array delimited by Carriage Return/Line Feed.
    lines = fileText.Split(vbCrLf)

    ' Close the stream reader
    sr.Close()

    ' Return
    Dim sw As New System.IO.Filestream("C:\test1.txt", IO.FileMode.Create)
    Dim w as New System.IO.Streamwriter(sw)
    Dim i as integer

    for i=0 to Ubound(lines)
    if lines(i).length > 1 then
    w.Write(lines(i))
    w.Flush()
    end if
    next
    sw.Close()
    End If

    End Sub
    End Module


    </code>

    this following vbscript works - but I need it in .NET

    Const ForReading = 1
    Const ForWriting = 2

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile("C:\test.txt", ForReading)

    strContents = objFile.ReadAll()
    objFile.Close

    strNewText = vbCrLf & vbCrLf
    strOldText = vbCrLf & vbCrLf & vbCrLf
    strOldText1 = vbCrLf & vbCrLf & vbCrLf & vbCrLf
    strOldText2 = vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf
    strOldText3 = vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf

    strContents1 = Replace(strContents, strOldText3, strNewText)
    strContents2 = Replace(strContents1, strOldText2, strNewText)
    strContents3 = Replace(strContents2, strOldText1, strNewText)
    strContents = Replace(strContents3, strOldText, strNewText)

    Set objFile = objFSO.OpenTextFile("C:\test1.txt", ForWriting)
    objFile.Write strContents
    objFile.Close


    Thanks for any help.

    Terry B

  2. #2
    Join Date
    Nov 2003
    Location
    Portland, OR
    Posts
    8,387
    Code:
    ' Create an empty string array to return to caller.
    Dim lines() As String = {}
    
    ' Check to see if the file exists.
    Dim FileName As String = "c:\test.txt"
    If File.Exists(FileName) Then
        ' Open a stream reader to get the text from the file.
        Dim sr As New StreamReader(FileName)
        ' Read all the file text.
        Dim fileText As String = sr.ReadToEnd()
        ' Close the stream reader
        sr.Close()
    
        ' Split the text into a string array delimited by Carriage Return/Line Feed.
        lines = Split(fileText, vbCrLf)
    
        ' Return
        Dim fs As New FileStream("c:\test1.txt", FileMode.Create)
        Dim sw As New StreamWriter(fs)
    
        Dim foundBlank As Boolean
        For Each line As String In lines
            If Line.Length > 0 Then
                sw.WriteLine (Line)
                ' Reset blank line flag
                foundBlank = False
            Else
                If Not foundBlank Then
                    ' Blank line: write first one
                    sw.WriteLine (Line)
                    ' Set flag to indicate that blank line was found
                    foundBlank = True
                End If
            End If
        Next
        sw.Close()
        fs.Close()
    End If
    Phil Weber
    http://www.philweber.com

    Please post questions to the forums, where others may benefit.
    I do not offer free assistance by e-mail. Thank you!

  3. #3
    Join Date
    Aug 2005
    Posts
    22

    Talking How about this?

    You have a way of removing all of the blank lines from the array. Pass that array into this subroutine:

    Code:
    'PASS THIS SUBROUTINE YOUR ARRAY OF LINES WITHOUT ANY BLANK LINES
    		'IN BETWEEN - THIS WILL ADD THE NECESSARY BLANK LINES
    		Private Sub InsertBlankLines(ByRef passedLines() As String)
    			Dim s As String = ""
    			Dim blank As String = " "
    			Dim count As Integer = passedLines.Length * 2
    			Dim newLines(count) As String
    			Dim i As Integer = 0
    			For Each s In passedLines
    				newLines(i) = s
    				newLines(i + 1) = " "
    				i = i + 2
    			Next
    			passedLines = newLines
    		End Sub
    This takes the passed array by reference, creates a new array twice the size as the original, cycles through all of the lines of the array placing blank lines in between the lines with text. By removing all blank lines in the array and then placing your own in you will not have to keep count of which lines are blank or not and/or which may or may not have had blank lines preceeding or following them.

    Let me know if this helps...
    Last edited by str_test; 09-23-2005 at 10:28 AM.

  4. #4
    Join Date
    Feb 2010
    Posts
    1

    quick way

    you can loop until there is no extra 2 lines.

    words="word1" & vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf & " word2"
    strNewText = vbCrLf
    strOldText = vbCrLf & vbCrLf
    continueLoop=1
    while continueLoop>0
    continueLoop=instr(words,strOldText)
    if continueLoop>0 then
    words= Replace(words, strOldText, strNewText )
    end if
    wend

    ' output result replace vbCrLf with <BR/>
    response.write replace(words,vbCrLf,"<BR/>")

    the result will be :-

    Word1
    Word2

  5. #5
    Join Date
    Feb 2004
    Location
    Longueuil, Québec
    Posts
    577
    No need for an array of Strings, which is very hard on resources. And no need to loop through all the lines.

    There is a Replace command on the String class. Simply replace all the double CrLf by a single CrLf, looping until the size stops changing, something like

    Code:
    Dim length As Long
    While length <> fileText.Length
        length = fileText.Length
        fileText = fileText.Replace(Environment.NewLine & Environment.NewLine, Environment.NewLine)
    End While
    Also note that although vbCrLf works, it is a good habit to use Environment.Newline instead.

    vbCrLf exists only in VB. Environment.NewLine comes from the framework itself and can be used in any language. Also, Environment.NewLine is multiplatform, while vbCrLf works only in Windows.

    By using Environment.NewLine, you write code that is more easily portable from one language to another. And you help yourself. If you ever have to program in another .NET language, the transition will be easier because you will have learned how to do things the .NET way, not only the VB way.

    And this holds a lot of things, such as using MessageBox.Show instead of MsgBox; using String.Substring instead of Left, Right and Mid, etc.

    I took that habit from the start in VB.NET, and god was I glad I had done so when I had to learn C#. I was already half in.

    And while we are at it, give a look at what is in Environment. That class is a little treasure.
    Jacques Bourgeois
    JBFI
    http://www3.sympatico.ca/jbfi/homeus.htm

Similar Threads

  1. Replies: 1
    Last Post: 10-24-2002, 02:59 AM
  2. Replies: 0
    Last Post: 07-08-2002, 12:37 PM
  3. Replies: 1
    Last Post: 03-27-2002, 09:01 AM
  4. File uploading / objFile.Write problem
    By Tomer Cagan in forum ASP.NET
    Replies: 1
    Last Post: 07-24-2001, 10:01 AM
  5. Replies: 3
    Last Post: 05-31-2000, 11:30 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center