Guide Contents
|
DigitalDan Home Page
|
Private Shared Function ReadCsv(filename As String) As List(Of String())
Dim ret As New List(Of String()) : ret.Clear()
Try
Using tfp As New FileIO.TextFieldParser(filename) With {.Delimiters = New String() {","}, .TextFieldType = FileIO.FieldType.Delimited}
While Not tfp.EndOfData
ret.Add(tfp.ReadFields())
End While
End Using
Catch ex As Exception
' handle the file error here
End Try
Return ret
End Function
Private Shared Function SplitCsv(record As String) As List(Of String)
Dim ret As New List(Of String) : ret.Clear()
Dim start As Integer = 1
Dim insideQuotes As Boolean = False
Dim c As Char
Dim field As String
For i As Integer = 1 To record.Length
c = CChar(Mid(record, i, 1))
If c = """"c Then insideQuotes = Not insideQuotes
If (c = ","c) AndAlso Not insideQuotes Then
ret.Add(Mid(record, start, i - start))
start = i + 1
End If
Next
If start <= record.Length Then
ret.Add(Mid(record, start))
End If
For i As Integer = 0 To ret.Count - 1
field = ret.Item(i).Trim
If Mid(field, 1, 1) = """" AndAlso Mid(field, field.Length, 1) = """" Then field = Mid(field, 2, field.Length - 2)
field = field.Replace("""""", """")
ret.Item(i) = field
Next
Return ret
End Function
Private Shared Function WriteCsv(filename As String, records As List(Of String())) As String
Dim errorMessage As String = ""
Dim regex1 As New System.Text.RegularExpressions.Regex("^x20-x7f")
Try
Using sw As New IO.StreamWriter(filename, False)
For Each record As String() In records
sw.WriteLine(Build_CSV_line(record))
Next
End Using
Catch ex As Exception
errorMessage = ex.Message
End Try
Return errorMessage
End Function
Private Shared Function Build_CSV_line(parts() As String) As String
Dim field As String
Dim needsQuotes As Boolean
Dim regex1 As New System.Text.RegularExpressions.Regex("^x20-x7f")
For i As Integer = 0 To parts.Length - 1
needsQuotes = False
field = parts(i)
If field.Contains(""""c) Then field = field.Replace("""", """""") : needsQuotes = True
If field.Contains(","c) OrElse field.Contains("'"c) Then needsQuotes = True
If field <> field.Trim Then needsQuotes = True
If regex1.IsMatch(field) Then needsQuotes = True
If needsQuotes Then parts(i) = """" & field & """"
Next
Return String.Join(","c, parts)
End Function
Private Shared Function Build_CSV_line1(parts() As String) As String
For i As Integer = 0 To parts.Length - 1
parts(i) = """" & parts(i).Replace("""", """""") & """"
Next
Return String.Join(","c, parts)
End Function