无法获取最后一行数据

问题描述:

在我的ASP.NET应用程序中,我需要读取CSV文件并插入到sql服务器中。无法获取最后一行数据

奇怪的是,它将第一行(column name)视为LineNumber=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 
+0

CurrentRecord永远不会设置。在尝试使其更具可读性时,您是否误删了它? – WozzeC

+0

对不起复制和粘贴错误...已经添加“CurrentRecord = afile.ReadFields”我的代码 –

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

无论如何,显然TextFieldParser中的最后一行是-1,而不是LastRowWithValuesIndex + 1.那么会发生什么呢。

  1. 你读的最后一行的数据(这是罚款)
  2. 读者跳到下一行准备下一行读(这是好的)
  3. 你得到的afile.LineNumber ,现在设置到下一行。这是-1 在这一点上。 (这是愚蠢的,虽然可以理解,不是你的错)
  4. 你的if语句不会让你进来,因为你在线-1。
  5. 循环结束,跳过CSV中的最后一行。

所有你需要做的就是读取数据之前先阅读该行的行号:

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

非常感谢... –