2012-03-18 33 views
1

我有以下一段代碼,我正在使用它來嘗試翻譯一個csv文件並將其轉換爲數據表。我的問題是調試器永遠不會使它返回到聲明。所有東西都正確地追加到數據表中,所以我知道該部分有效。任何想法,我可以做什麼來進一步解決這個問題。另外,如果你知道一個簡單的方法將一個csv文件導入到一個數據表,我會非常有興趣瞭解它。在try語句中返回數據表的麻煩

謝謝!

Public Function loadCSVTableII() As DataTable 

    Dim dt As New DataTable("TableII") 
    Dim line As String = String.Empty 
    Dim counter As Integer = 0 
    Dim reader As New StreamReader(pathTableTwo) 

    Try 
     While Not IsNothing(line) 
      line = reader.ReadLine() 
      Dim lineSep As String() = line.Split(New Char() {","c}) 

      If Not counter = 0 Then 
       dt.Rows.Add(lineSep) 
       counter += 1 
      Else 
       For Each value As String In lineSep 
        dt.Columns.Add(value) 
       Next 
       counter += 1 
      End If 
     End While 

     'cursor never gets to this code block... 
     Dim primarykey(0) As DataColumn 
     primarykey(0) = dt.Columns("Ages") 
     dt.PrimaryKey = primarykey 

     Return dt 

    Catch ex As Exception 
     Throw 
    End Try 

End Function 

更新:它在代碼中的這一行上出錯。

Dim lineSep As String() = line.Split(New Char() {","c}) 

它說對象引用未設置爲對象的實例。奇怪的是,它可以在整個數據表中正常工作。難道是while循環沒有終止在文件的末尾?

回答

1

嘗試更改您的While循環以處理流條件結束。目前還不清楚IsNothing函數在代碼中的作用。

While Not reader.EndOfStream 
    line = reader.ReadLine 
    '// Dim lineSep As String() = line.Split(New Char() {","c}) 

爲了您的線分離,在VB.Net,它是簡單的只是這樣做:

Dim lineSep As String() = line.Split(",") 
+0

非常感謝您!這解決了問題。 – 2012-03-18 18:39:27

1

您可以使用OLEDB提供商。

string query = "SELECT Symbol, [Name of Company], FROM [just file name with extension]"; 
      string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + [csv file path without file name] + ";" + "Extended Properties=’text;HDR=YES;’"; 

      //create dataadapter object 
      OleDbDataAdapter adapter = new OleDbDataAdapter(query, connStr); 

      // create table 
      DataTable dtSymbolDetails = new DataTable("ScriptDetails"); 
      dtSymbolDetails.Columns.Add("Symbol"); 
      dtSymbolDetails.Columns.Add("Name of Company"); 

      // fill the table with data using adapter 
      adapter.Fill(dtDetails);