Read only particular fields from CSV File in vb.net - vb.net

I have this code to read a CVS file. It reads each line, devides each line by delimiter ',' and stored the field values in array 'strline()' .
How do I extract only required fields from the CSV file?
For example if I have a CSV File like
Type,Group,No,Sequence No,Row No,Date (newline)
0,Admin,3,345678,1,26052010 (newline)
1,Staff,5,78654,3,26052010
I Need only the value of columns Group,Sequence No and date.
Thanks in advance for any ideas.
Dim myStream As StreamReader = Nothing
' Hold the Parsed Data
Dim strlines() As String
Dim strline() As String
Try
myStream = File.OpenText(OpenFile.FileName)
If (myStream IsNot Nothing) Then
' Hold the amount of lines already read in a 'counter-variable'
Dim placeholder As Integer = 0
strlines = myStream.ReadToEnd().Split(Environment.NewLine)
Do While strlines.Length <> -1 ' Is -1 when no data exists on the next line of the CSV file
strline = strlines(placeholder).Split(",")
placeholder += 1
Loop
End If
Catch ex As Exception
LogErrorException(ex)
Finally
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try

1) DO NOT USE String.Split!!
CSV data can contain comma's, e.g.
id,name
1,foo
2,"hans, bar"
Also as above you would need to handle quoted fields etc... See CSV Info for more details.
2) Check out TextFieldParser - it hadles all this sort of thing.
It will handle the myriad of different escapes you can't do with string.split...
Sample from: http://msdn.microsoft.com/en-us/library/cakac7e6.aspx
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\TestFolder\test.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
End Using
The MyReader.ReadFields() part will get you an array of strings, from there you'll need to use the index etc...
PK :-)

Maybe instead of only importing selected fields, you should import everything, then only use the ones you need.

Related

FileIO.TextFieldParser get unaltered row for reporting on failed parse

I want to output the current row if there is an error but I'm getting a message that the current record is nothing.
Here is my code:
Dim currentRow As String()
Using MyReader As New FileIO.TextFieldParser(filenametoimport)
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
ImportLine(currentRow)
Catch ex As FileIO.MalformedLineException
report.AppendLine()
report.AppendLine($"[{currentrow}]")
report.AppendLine("- record is malformed and will be skipped. ")
Continue While
End Try
End While
end Using
I need to output the currentrow so that I can report to the user that there was a bad record.
report.AppendLine($"[{currentrow}]")
I understand that the value would be null if the parse failed but is there a way to get the current record?
How do I output this record if it failed to parse the record?
Thanks for the assistance!
You can't get the raw data directly in the exception, but you can at least get the line number where the error occurred. You may be able to use that line number to go back and find the offending record:
Dim currentRow As String()
Using MyReader As New FileIO.TextFieldParser(filenametoimport)
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
ImportLine(currentRow)
Catch ex As FileIO.MalformedLineException
report.AppendLine($"{vbCrLf}- record at line {ex.LineNumber} is malformed and will be skipped. ")
End Try
End While
End Using
TextFieldParser also provides access to the underlying stream, and provides a ReadLine() method, so if you're really desparate to write the code you could walk back the stream to the previous line ending and then call MyReader.ReadLine() to get the record (which would in turn advance the stream again to where you expect).
I did not get a compile error on MyReader.SetDelimiters(",") but I changed it to an array anyway. The report.AppendLine($"[{currentrow}]") line probably doesn't expect an array. That line I altered to provide a string.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim currentRow As String() = Nothing
Using MyReader As New FileIO.TextFieldParser("filenametoimport")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters({","})
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
ImportLine(currentRow)
Catch ex As FileIO.MalformedLineException
report.AppendLine()
report.AppendLine($"[{String.Join(",", currentRow)}]")
report.AppendLine("- record is malformed and will be skipped. ")
Continue While
End Try
End While
End Using
End Sub
EDIT
As per comments by # Joel Coehoorn and # ErocM if the row is null you could provide the content of the previous row so they errant row could be located.
Dim LastGoodRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
ImportLine(currentRow)
LastGoodRow = currentRow
Catch ex As FileIO.MalformedLineException
report.AppendLine()
report.AppendLine($"[{String.Join(",", LastGoodRow)}]")
report.AppendLine("- record following this row is malformed and will be skipped. ")
Continue While
End Try
End While

Working with commas in a comma delimited file

I have a vb project that imports a csv file and some of the data contains commas. The fields with the commas are in double quotes.
I am creating a datagridview from the header row of the csv then importing the remainder of the file into the dgv but the fields with commas are causing a problem. The fields are not fixed width.
I think I need a way to qualify the commas as a delimiter based on double quote or some other method of importing the data into the dgv.
Thanks
Using objReader As New StreamReader(FName)
Dim line As String = objReader.ReadLine()
Do While objReader.Peek() <> -1
line = objReader.ReadLine()
Dim splitLine() As String = line.Split(",")
DataGridView1.Rows.Add(splitLine)
Application.DoEvents()
Loop
End Using
Example Data:
1,"VALIDFLAG, NOGPS",0,1.34,3.40,0.17,1
Thinks very much for the suggestions.
I am going to use textfieldparser for my import.
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(FName)
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String()
Dim firstline As Boolean = True
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
If firstline = True Then
firstline = False
Else
Me.DataGridView1.Rows.Add(currentRow)
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
Application.DoEvents()
End While
End Using

I used FSO to get a file name. But I need the path too. Is it possible to get the path using FSO?

Here is the code I'm using. Hope that it helps pinpoint the area where I need help.
Private Sub readCVS_file()
Using MyReader As New Microsoft.VisualBasic.
FileIO.TextFieldParser(
GetTempPath() + "output.tmp")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
'get file path using currentField. First field is program name
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid.")
End Try
End While
End Using
End Sub
After reading the current field, I want to get the path to the filename (filename is the first field in output.tmp text file.)
Thanks for any help...

VB.NET read only some cells for each row from csv file

I have a csv file that has the following structure :
id,name,adress,email,age
1,john,1 str xxxx,john#gmail.com,19
2,mike,2 bd xxxx,mike#gmail.com,21
3,jeana,1 str ssss,jeana#gmail.com,18
.......................
.......................
What I would like to do is to read the csv file, skip the first line (contains headers) and extract the 2nd, 3rd and 4th data from each row and populate a datagridview.
This is the code I'm using however it brings me all the csv content :
DataGridView1.ColumnCount = 4
DataGridView1.Columns(0).Name = "ID"
DataGridView1.Columns(1).Name = "NAME"
DataGridView1.Columns(2).Name = "ADRESS"
DataGridView1.Columns(3).Name = "AGE"
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser _
(openFile.FileName)//the csv path
'Specify that reading from a comma-delimited file'
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
With DataGridView1.Rows.Add(currentRow) 'Add new row to data gridview'
End With
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
End Using
So can someone show me how to do that?
Thanks.
It could be simple as reading the first line and discard it, Then start to read the real data from your file
Using MyReader As New TextFieldParser(openFile.FileName)
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
' Read the first line and do nothing with it
If Not MyReader.EndOfData Then
currentRow = MyReader.ReadFields()
End If
While Not MyReader.EndOfData
Try
' Read again the file
currentRow = MyReader.ReadFields()
DataGridView1.Rows.Add(currentRow(1), currentRow(2),currentRow(3))
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
End Using
EDIT Seeing your comment below then I have changed the line that add the row to add only the strings at position 1,2 and 3. This of course is different from the columns added to the DataGridView. It is not clear if you want to change these columns to contains only these 3 fields. If you still want the column for ID and AGE in the grid you could change the Add to
DataGridView1.Rows.Add("", currentRow(1), currentRow(2),currentRow(3), "")

How to omit the last comma while importing to access DB?

Well, I have successfully coded my unformatted text data. I used comma as a delimiter and if I am posting it here so that it can help students like me.
Try
Using Reader As New TextFieldParser(Application.StartupPath & "\data.txt")
Reader.TextFieldType = FieldType.FixedWidth
Reader.SetFieldWidths(20, 20, 1, 2)
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim oWrite As New System.IO.StreamWriter(Application.StartupPath & "\FormattedData.txt")
For Each newString In currentRow
oWrite.Write(newString & ",")
Next
oWrite.WriteLine()
oWrite.Close()
Catch ex As Exception
End Try
End While
End Using
Catch ex As Exception
End Try
Now I have a question too: How can I omit the last comma from the output while importing to access database?
The easiest way to do this (that I have found) is to write the comma for the last record on the next pass, but don't do it on the first loop:
Dim fFirstEntry As Boolean = True
For Each newString In currentRow
If fFirstEntry Then
fFirstEntry = False
Else
oWrite.Write(",")
End If
oWrite.Write(newString)
Next
Dim sb As New StringBuilder()
For Each newString In currentRow
sb.Append(newString).Append(",")
Next
sb.Length -= 1
oWrite.Write(sb.ToString())
Note that the StringBuilder is more efficient than direct string manipulation. The latter generates a lot of garbage on the heap, which has to be collected by the garbage collector later.