Saturday, October 29, 2011

Remove empty rows in text files? Solved

A small code snippet may be very useful in many situations to remove empty rows in text files. Here is the code:
First: in Form1 insert a label by which you indicate to user the directory  where is the converted file: ie C:\beta.tex
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim objFileToRead, objFileToWrite, objFSO, strPathWrite
        Try
            OpenFileDialog1.FileName = ""
            OpenFileDialog1.Filter = "Text files .txt|*.txt"
            Me.OpenFileDialog1.ShowDialog()
            strPathWrite = "C:\beta.txt"

            objFSO = CreateObject("Scripting.FileSystemObject")

            objFileToRead = objFSO.OpenTextFile(OpenFileDialog1.FileName, 1)
            objFileToWrite = objFSO.OpenTextFile(strPathWrite, 2, True)


            Dim strTemp
            Do While Not objFileToRead.AtEndOfStream
                strTemp = objFileToRead.ReadLine
                If strTemp <> "" Then
                    objFileToWrite.WriteLine(strTemp)
                End If
            Loop


            objFileToRead.Close()
            objFileToWrite.Close()
            objFileToRead = Nothing
            objFileToWrite = Nothing
            objFSO = Nothing

        Catch
            Me.Label1.Text = "You haven't chosed any file"
            Me.Label1.TextAlign = Drawing.ContentAlignment.MiddleCenter
            Me.Label1.Left = (Me.Width - Me.Label1.Width) / 2
        End Try

    End Sub

No comments:

Post a Comment