Removing Columns From Delimited Text File

Greetings,

I need to parse a delimited text file and remove the last 3 fields in each row.

Can someone show me how to reference the columns and specify the ones I want to keep

Thanks.



Answer this question

Removing Columns From Delimited Text File

  • Claudiu Chiorean

    Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal _

    e As System.EventArgs) Handles Button1.Click

    Using MyReader As New _

    Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")

    MyReader.TextFieldType = FileIO.FieldType.Delimited

    MyReader.SetDelimiters(",")

    Dim currentRow As String()

    While Not MyReader.EndOfData

    Try

    Dim x As Integer = 0

    currentRow = MyReader.ReadFields()

    Dim currentField As String

    For Each currentField In currentRow

    If x < currentRow.Length - 4 Then

    TextBox1.AppendText(currentField & ",")

    End If

    x += 1

    Next

    TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1)

    TextBox1.AppendText(vbCrLf)

    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException

    MsgBox("Line " & ex.Message & _

    "is not valid and will be skipped.")

    End Try

    End While

    End Using

    End Sub

    End Class



  • Pablo Alvarez Jalon

    Try this:

    Dim stmReader As System.IO.FileStream = System.IO.File.Open("C:\1.txt", IO.FileMode.Open)

    Dim rdrReader As System.IO.TextReader = New System.IO.StreamReader(stmReader)

    Dim strLine As String

    Dim intCounter As Integer

    Do Until (rdrReader.Peek() = -1) 'Not end of file

    strLine = rdrReader.ReadLine()

    For intCounter = 1 To 3

    If strLine.IndexOf(",") <> -1 Then

    'Delimiter exists, remove all string after delimiter

    strLine = strLine.Remove(strLine.LastIndexOf(","))

    Else

    'Only one column, remove it

    strLine = ""

    End If

    Next

    MsgBox(strLine)

    Loop

    rdrReader.Close()

    rdrReader.Dispose()

    rdrReader = Nothing

    stmReader.Close()

    stmReader.Dispose()

    stmReader = Nothing

    Hope this can Help!

    Best Regards,

    Amr Ouf

  • Removing Columns From Delimited Text File