Private Function DeLimitFile(ByVal FileName As String, ByVal Delimiter As Char, ByVal RowHeader As Boolean) As DataTable
'string that should (hopefully) not occur in the file,
'used to replace the delimiter that is inside of quotes to ease splitting
Dim AltDelimiter As String = "GeorgE W. BusH AnD JohN KerrY WerE HappilY MarrieD TodaY..."
'string to hold final delimiter string, for special escape sequence characters needed in regex
Dim FinalDelimiter As String
If Delimiter = Convert.ToChar(9) Then
'special character sequence for regex to represent a tab in the regex pattern
FinalDelimiter = "\t"
Else
FinalDelimiter = Delimiter
End If
Dim HeaderFlag As Boolean = RowHeader 'flag to indicate if rowheaders are present
Dim Pattern As String = "(?<="")[^" & FinalDelimiter & "].*?[^" & FinalDelimiter & "](?="")"
Dim Regex As New System.Text.RegularExpressions.Regex(Pattern)
Dim MyReader As New System.IO.StreamReader(FileName) 'opens file for reading
Dim MyTable As New DataTable 'to hold resulting data
Dim GetRowCount As Boolean = True 'flag to get first line column count
While MyReader.Peek <> -1
Dim MyLine As String = MyReader.ReadLine
Dim MyMatches As System.Text.RegularExpressions.MatchCollection = Regex.Matches(MyLine)
'replaces delimiters inside of quotes, to ease splits
For Each Match As System.Text.RegularExpressions.Match In MyMatches
Dim NewString As String = Match.Value.Replace(FinalDelimiter, AltDelimiter)
MyLine = MyLine.Replace("""" & Match.Value & """", NewString)
Next
'splits the string on the delimiter, each regular delimiter should now be a column
Dim Splits() As String = System.Text.RegularExpressions.Regex.Split(MyLine, FinalDelimiter)
'dont know number of columns until the first line is done parsing, so here we
'get the number of columns in the datatable and add them
If GetRowCount = True Then
For I As Integer = 0 To Splits.GetLength(0) - 1
Dim MyColumn As New DataColumn
'adds Column Headers if RowHeader is True
If HeaderFlag = True Then
MyColumn.ColumnName = Splits(I)
End If
MyTable.Columns.Add(MyColumn)
Next
GetRowCount = False
End If
'adds data in the array into the data row, replacing the alternate delimiter back to original
Dim MyRow As DataRow
If HeaderFlag = False Then
'its ok to add to add to table
For X As Integer = 0 To Splits.GetLength(0) - 1
Splits(X) = Splits(X).Replace(AltDelimiter, FinalDelimiter)
Next
MyTable.Rows.Add(Splits)
Else
'its a header row, so dont bother adding it and set flag to false
HeaderFlag = False
End If
End While
MyReader.Close()
Return MyTable
End Function