Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 无法获取最后一行数据_Asp.net_Vb.net_Csv_Row - Fatal编程技术网

Asp.net 无法获取最后一行数据

Asp.net 无法获取最后一行数据,asp.net,vb.net,csv,row,Asp.net,Vb.net,Csv,Row,在我的ASP.NET应用程序中,我需要读取CSV文件并插入sql server 奇怪的是,它将第一行(列名)视为行号=2 但是我发现我的代码无法读取CSV文件的最后一行 Dim CSV_content As String = "" Dim CSVFilePathName As String = Server.MapPath("~/XXX/" & filename) If File.Exists(CSVFilePathName) = True Then

在我的ASP.NET应用程序中,我需要读取CSV文件并插入sql server

奇怪的是,它将第一行(
列名
)视为
行号=2

但是我发现我的代码无法读取CSV文件的最后一行

    Dim CSV_content As String = ""
    Dim CSVFilePathName As String = Server.MapPath("~/XXX/" & filename)

    If File.Exists(CSVFilePathName) = True Then
        'Response.Write("exists")

        Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(CSVFilePathName)
        Dim CurrentRecord As String()
        afile.TextFieldType = FileIO.FieldType.Delimited
        afile.Delimiters = New String() {","}
        afile.HasFieldsEnclosedInQuotes = True

        Dim LastName As String = ""
        Dim FirstName As String = ""
        Dim DisplayName As String = ""
        Dim EmailName As String = ""

        Dim dc As New dcHRISDataContext

        ' parse the actual file
        Do While Not afile.EndOfData

            Try

CurrentRecord = afile.ReadFields

                'insert into tmp db
                If afile.LineNumber > 2 Then

                    Dim newRecord1 As New XXX
                    dc.XXX.InsertOnSubmit(newRecord1)

                    newRecord1.LastName = CurrentRecord(0).Trim
                    newRecord1.FirstName = CurrentRecord(1).Trim
                    newRecord1.DisplayName = CurrentRecord(1).Trim
                    newRecord1.DirEmail = CurrentRecord(3).Trim
                    newRecord1.GetFileDate = DateTime.Now
                    newRecord1.GetFileName = filename
                    dc.SubmitChanges()
                End If

                                Catch ex As FileIO.MalformedLineException
                Stop
            End Try
        Loop
    End If  

哇,这是我见过的最愚蠢的问题

无论如何,显然TextFieldParser中的最后一行是-1,而不是ValuesIndex+1的最后一行。所以发生的就是这样

  • 读取最后一行的数据(这很好)
  • 读卡器跳到下一行,准备下一行阅读(这很好)
  • 获得afile.LineNumber,现在设置为下一行。这是-1 在这一点上。(这是愚蠢的,虽然可以理解,但不是你的错)
  • 你的if语句不会让你进去,因为你在第1行
  • 循环结束,跳过CSV中的最后一行
  • 在读取数据之前,您只需读取行的行号:

    Dim i As Integer = afile.LineNumber
    CurrentRecord = afile.ReadFields
    If i > 2 Then
    etc
    

    CurrentRecord从未设置过。您是否在试图使其更具可读性时错误地删除了它?很抱歉复制粘贴错误。。。在我的代码中添加了“CurrentRecord=afile.ReadFields”