在我的ASP.NET应用程序中,我需要读取CSV文件并插入到sql server中。
奇怪的是,它将第一行(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 :(得分:0)
无论如何,显然TextFieldParser中的最后一行是-1,而不是LastRowWithValuesIndex + 1.那么会发生什么呢。
您所要做的就是在读取数据之前读取行的行号:
Dim i As Integer = afile.LineNumber
CurrentRecord = afile.ReadFields
If i > 2 Then
etc