I am trying to upload tracks to my SQL database via a CSV file, but when I try to process the file, I get this exception:
System.FormatException
HResult=0x80131537
Message=String was not recognized as a valid TimeSpan.
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
Neither formatting time as hh:mm:ss
or h:mm:ss
works, though my CSV is very simple; a record looks like this:
TrackName,TrackLength,TrackNumber,AlbumID
Elected,00:04:05,3,6
My code is also very simple; it has worked for converting numbers and DateTimes. What am I doing wrong with the TimeSpans? I've been Googling a lot, but all I've found says TimeSpan.Parse
is the best method for converting strings to timespans.
Dim csvData = From line As String In File.ReadAllLines(filenameWithPath)
Skip 1
Let CR = line.Split(",")
Select New Track With {
.TrackName = CR(0),
.TrackLength = TimeSpan.Parse(CR(1)),
.TrackNumber = CInt(CR(2)),
.AlbumID = CInt(CR(3))
}
EDIT: There is no reason for an exception to be thrown. Below is the full code for my button click event; there's only a simple If statement to check if the file upload control has a file. Nothing here should be causing problems.
Private Sub BTN_Upload_Click(sender As Object, e As EventArgs) Handles BTN_Upload.Click
If FU_CSV.HasFile Then
Dim filenameWithPath As String = Server.MapPath("~/Content/Docs/Data/" & FU_CSV.FileName)
FU_CSV.SaveAs(filenameWithPath)
Dim csvData = From line As String In File.ReadAllLines(filenameWithPath)
Skip 1
Let CR = line.Split(",")
Select New Track With {
.TrackName = CR(0),
.TrackLength = TimeSpan.Parse(CR(1)),
.TrackNumber = CInt(CR(2)),
.AlbumID = CInt(CR(3))
}
For Each t As Track In csvData
context.Tracks.Add(t)
context.SaveChanges()
Next
End If
End Sub
User contributions licensed under CC BY-SA 3.0