在VB.net中将csv数据转换为DataTable,从第0行捕获列名

在VB.net中将csv数据转换为DataTable,从第0行捕获列名,vb.net,csv,import,datatable,Vb.net,Csv,Import,Datatable,我已经改编了@tim schmelter问题答案中的代码(见下文) 我想解析csv文件第0行的列标题 DT|Meter Number|Customer Account Number|Serial Number|Port... 但我想不出怎么做,运气不好。如有任何建议,将不胜感激 Public Function csvToDatatable_2(ByVal filename As String, ByVal separator As String) '//////////////////

我已经改编了@tim schmelter问题答案中的代码(见下文)

我想解析csv文件第0行的列标题

DT|Meter Number|Customer Account Number|Serial Number|Port...
但我想不出怎么做,运气不好。如有任何建议,将不胜感激

Public Function csvToDatatable_2(ByVal filename As String, ByVal separator As String)
    '////////////////////////////////////////
    'Reads a selected txt or csv file into a datatable 
    'based on code from  http://stackoverflow.com/questions/11118678/convert-csv-data-to-datatable-in-vb-net
    '////////////////////////////////////////
    Dim dt As System.Data.DataTable

    Try
        dt = New System.Data.DataTable
        Dim lines = IO.File.ReadAllLines(filename)
        Dim colCount = lines.First.Split(separator).Length

        For i As Int32 = 1 To colCount
            dt.Columns.Add(New DataColumn("Column_" & i, GetType(String)))
        Next

        For Each line In lines
            Dim objFields = From field In line.Split(separator)
            Dim newRow = dt.Rows.Add()
            newRow.ItemArray = objFields.ToArray()
        Next

    Catch ex As Exception
        Main.Msg2User(ex.Message.ToString)
        Return Nothing

    End Try

    Return dt

End Function

只需在文件的所有行中循环。使用布尔值检查第一行

Public Function csvToDatatable_2(ByVal filename As String, ByVal separator As String)
 Dim dt As New System.Data.DataTable
 Dim firstLine As Boolean = True
 If IO.File.Exists(filename) Then
   Using sr As New StreamReader(filename) 
     While Not sr.EndOfStream
       If firstLine Then
         firstLine = False
         Dim cols = sr.ReadLine.Split(separator)
         For Each col In cols 
           dt.Columns.Add(New DataColumn(col, GetType(String)))
         Next
       Else
         Dim data() As String = sr.Readline.Split(separator)
         dt.Rows.Add(data.ToArray)
       End If
      End While
   End Using
 End If
 Return dt
End Function

以下是上述两种解决方案的混合,还有一些其他变化:

Public Shared Function FileToTable(ByVal fileName As String, ByVal separator As String, isFirstRowHeader As Boolean) As DataTable
  Dim result As DataTable = Nothing
  Try
    If Not System.IO.File.Exists(fileName) Then Throw New ArgumentException("fileName", String.Format("The file does not exist : {0}", fileName))
    Dim dt As New System.Data.DataTable
    Dim isFirstLine As Boolean = True
    Using sr As New System.IO.StreamReader(fileName)
      While Not sr.EndOfStream
        Dim data() As String = sr.ReadLine.Split(separator, StringSplitOptions.None)
        If isFirstLine Then
          If isFirstRowHeader Then
            For Each columnName As String In data
              dt.Columns.Add(New DataColumn(columnName, GetType(String)))
            Next
            isFirstLine = True ' Signal that this row is NOT to be considered as data.
          Else
            For i As Integer = 1 To data.Length
              dt.Columns.Add(New DataColumn(String.Format("Column_{0}", i), GetType(String)))
            Next
            isFirstLine = False ' Signal that this row IS to be considered as data.
          End If
        End If
        If Not isFirstLine Then
          dt.Rows.Add(data.ToArray)
        End If
        isFirstLine = False ' All subsequent lines shall be considered as data.
      End While
    End Using
  Catch ex As Exception
    Throw New Exception(String.Format("{0}.CSVToDatatable Error", GetType(Table).FullName), ex)
  End Try
  Return result
End Function

谢谢,@OneFineDay,做得很好。一旦我修正了第9行的一个输入错误:
code
Dim cols=sr.ReadLine.Split(separator)如果你把这个方法变成csv字符串扩展方法,那也会很有趣。。。。