在try语句中返回数据表时遇到问题

时间:2012-03-18 16:26:11

标签: vb.net csv datatable streamreader

我有以下代码片段用于尝试翻录csv文件并将其转换为数据表。我的问题是调试器永远不会进入return语句。一切都正确附加到数据表,所以我知道该部分有效。任何想法都取决于我能做些什么来解决这个问题。此外,如果您知道将导入csv文件转换为数据表的更简单方法,我将非常有兴趣了解它。

谢谢!

    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}) 

它表示Object引用未设置为对象的实例。但奇怪的是,它可以很好地处理整个数据表。可能是while循环没有在文件末尾终止吗?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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(",")