Solved

How to INSERT, SORT, FILTER a CSV file in VB.NET

Posted on 2015-02-19
1
97 Views
Last Modified: 2015-08-24
I am trying to put to get a small program to randomly select a record from a CSV file.  The user would select the file and the program would filter the file on one column, insert a column of random numbers and then sort the file and select a number of record to be wirtten to an output file.

To select the file, I have the following:

 Private Sub btnBrowse1_Click(sender As Object, e As EventArgs) Handles btnBrowse1.Click
        Dim randomValue As Random = New Random
        Dim openFileDialog1 As New OpenFileDialog()


        openFileDialog1.Filter = "CSV Files|*.csv"
        openFileDialog1.Title = "Select a CSV File"

        Dim list As New List(Of String)

        If openFileDialog1.ShowDialog() = DialogResult.OK Then
            myFileName = openFileDialog1.FileName
            outputFile = myFileName.Replace(".csv", "_" & System.DateTime.Now.ToString("yyyyMMdd") & ".csv")
            txtCsvFile.Text = myFileName
        End If
    End Sub

To process the file I have this:

    Private Sub btnProcess_Click(sender As Object, e As EventArgs) Handles btnProcess.Click
        Dim sReader As StreamReader = New StreamReader(myFileName)
        Dim sWriter As StreamWriter = New StreamWriter(outputFile)
        Dim line As String
        Dim rv As Integer
        Dim recAmount As Integer
        Dim counter As Integer = 0

        ' Store contents in this String.
        ' Read first line.
        line = sReader.ReadLine
        recAmount = CInt(txtRecAmount.Text)

        MsgBox(randomValue.Next(1, 1000))

        ' Loop over each line in file, While list is Not Nothing.
        Do While sReader.Peek <> -1
            counter += 1
            line = sReader.ReadLine
            rv = randomValue.Next(1, 1000)

            Do While counter < recAmount + 1
                sWriter.WriteLine(rv & "," & line)
                Exit Do
                ' Read in the next line.
            Loop
        Loop
        sWriter.Close()
    End Sub

It doesn't filter or sort.  Do I need to read it into a two dimensional array? If so, how do I filter and sort the 2 dimensional array?
0
Comment
Question by:abuhaneef
1 Comment
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 40621199
You could use the TextFieldParser class to parse the CSV into separate elements, that you could sort on.

Example:

TextFieldParser Class
https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser(v=vs.110).aspx

Using MyReader As New Microsoft.VisualBasic.FileIO.
    TextFieldParser("c:\logs\bigfile")

    MyReader.TextFieldType = 
        Microsoft.VisualBasic.FileIO.FieldType.Delimited
    MyReader.Delimiters = New String() {vbTab}
    Dim currentRow As String()
    'Loop through all of the fields in the file.  
    'If any lines are corrupt, report an error and continue parsing.  
    While Not MyReader.EndOfData
        Try
            currentRow = MyReader.ReadFields()
            ' Include code here to handle the row. 
        Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
            MsgBox("Line " & ex.Message & 
            " is invalid.  Skipping")
        End Try 
    End While 
End Using

Open in new window

0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction When many people think of the WebBrowser (http://msdn.microsoft.com/en-us/library/2te2y1x6%28v=VS.85%29.aspx) control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
This video discusses moving either the default database or any database to a new volume.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now