• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 387
  • Last Modified:

Best Method To Remove Lines In Text File Using Visual Basic Or C#

I've got code that works spectacularly to parse a text file (Thanks Idle_Mind!!).  However, the text file has thrown a curve into the mix.  I'll put the link to the original post below.

The text file includes lines with a missing second column.  The resulting text file contains lines that begin with commas.  I require those lines that begin with commas removed from the final text files.

My first thought was to open the text files after they have been created, then look for lines that start with commas and remove them.  However, I realized there might be an easier way that I do not know.

http://www.experts-exchange.com/Programming/Languages/.NET/Q_26472802.html hotlist.txt  
Option Explicit On

Imports System
Imports System.IO
Imports System.IO.File
'Application runs invisibly
'There are 11 colomns, each represented by white space which is the start/end of each column
'Keep only those rows that contain the text "OH" in the 3rd column
'Keep only the following columns: 2, 3, 6, 7, 8, 9, and 11
'Output data to text files as comma sperated based on first character in column 11:
'   if column 11 starts with "V", create a file called "Stolen.txt"
'   if column 11 starts with "W", create a file called "Wanted.txt"
'   if column 11 starts with "P", create a file called "LP.txt"
'   if column 11 starts with "M", create a file called "MP.txt"

Public Class DOJ_Parser_Hilliard
    'Global variables
    Public strFileName As String = "hotlist.txt"
    Public strCurrent As String = Directory.GetCurrentDirectory()
    Public strGlobalFilePath As String = strCurrent & "\" & strFileName
    'LOAD Form, check for file existance
    Private Sub DOJ_Parser_Hilliard_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Label1.Text = "Loading . . ."

        If VerifyFileExists() = True Then
            MessageBox.Show("File not found.", "WARNING!")
        End If
    End Sub
    'PARSE DATA and write to files
    Private Sub ParseMe()

        MessageBox.Show("Data Extraction Commencing...", "PROCESSING")
        Dim Path As String = strCurrent
        Dim DataFile As String = strFileName
        Dim V_File As String = "Stolen.txt"
        Dim W_File As String = "Wanted.txt"
        Dim LP_File As String = "LP.txt"
        Dim MP_File As String = "MP.txt"

        Using sw_V As New StreamWriter(System.IO.Path.Combine(Path, V_File), False)
            Using sw_W As New StreamWriter(System.IO.Path.Combine(Path, W_File), False)
                Using sw_LP As New StreamWriter(System.IO.Path.Combine(Path, LP_File), False)
                    Using sw_MP As New StreamWriter(System.IO.Path.Combine(Path, MP_File), False)

                        Using sr As New StreamReader(System.IO.Path.Combine(Path, DataFile))
                            While Not sr.EndOfStream
                                Dim values As New List(Of String)
                                values.AddRange(sr.ReadLine.Split(" "))
                                If values(2).ToUpper = "0H" Then ' process lines with "OH" in the 3rd column
                                    ' remove columns indexed at: 0, 3, 4, 9
                                    Dim output As String = String.Join(",", values.ToArray)
                                    ' output to file based on first character of value in last colmun
                                    Select Case values(values.Count - 1).Substring(0, 1).ToUpper
                                        Case "V"
                                        Case "W"
                                        Case "P"
                                        Case "M"
                                    End Select
                                End If
                            End While
                        End Using

                    End Using
                End Using
            End Using
        End Using
    End Sub
    'VERIFY File Exists
    Private Function VerifyFileExists()
        'this function runs on form load and tries to find the specified file
            strCurrent = Directory.GetCurrentDirectory()
        Catch E As Exception
        End Try
        If Not Exists(strGlobalFilePath) Then
            MessageBox.Show("File Not Found.", "WARNING!")
            Return False
            Return True
        End If
    End Function
    'TIMER to control MessageBox
    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Timer1.Enabled = False  'end timer
        SendKeys.Send("{ESC}")  'send escape key press to messagebox
    End Sub
    'TIMER set length and start timer
    Private Sub MessageBoxTimer(ByVal intervalLength As Integer)
        'set length of time and start timer
        Timer1.Interval = intervalLength
        Timer1.Enabled = True
    End Sub

    'open a stream reader and remove lines that start with comma
    Private Sub test()
            ' Create an instance of StreamReader to read from a file.
            Dim sr As StreamReader = New StreamReader(strCurrent & "\Wanted.txt")
            Dim line As String
            ' Read and display the lines from the file until the end 
            ' of the file is reached.
                line = sr.ReadLine()

                'If line.Substring(0, 0) = "," Then  
                'Remove(2, line.Length - 1)
                'End If
            Loop Until line Is Nothing
        Catch E As Exception
            ' Let the user know what went wrong.
            MessageBox.Show("The file could not be read:")
        End Try
    End Sub
End Class

Open in new window

1 Solution
Mike TomlinsonMiddle School Assistant TeacherCommented:
Not sure I'm following 100% but it seems to me that you could simply change:

    If values(2).ToUpper = "0H" Then


    If values(2).ToUpper = "0H" AndAlso values(1).Trim <> "" Then

This will only allow lines that are NOT blank in the second column AND have "OH" in the third column to pass thru and be processed.
asc2010Author Commented:

Thank you so much!!  This is perfect and much more efficient than my approach!

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now