VB.NET remove extra blank lines from file
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

