I am trying to add multiple records to a database table using a CSV file. If I remove the try/catch, I get this error:
System.IO.FileNotFoundException
HResult=0x80070002
Message=Could not find file 'C:\Program Files (x86)\IIS Express\BJ_and_TS.csv'.
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
Why is it not saving the file? What else am I doing wrong? Here is my codebehind:
Private Sub BTN_Upload_Click(sender As Object, e As EventArgs) Handles BTN_Upload.Click
Dim context As New MusicContext
Try
If FU_CSV.HasFile Then
FU_CSV.SaveAs(Server.MapPath("~/Content/Docs/Data/" & FU_CSV.FileName))
Dim csvData = From line As String In File.ReadAllLines(FU_CSV.FileName)
Skip 1
Let CR = line.Split(",")
Select New Album With {
.AlbumName = CR(0),
.ImagePath = CR(1),
.ReleaseDate = CDate(CR(2)),
.UnitPrice = CDec(CR(3)),
.BandID = CInt(CR(4)),
.GenreID = CInt(CR(5))
}
For Each a As Album In csvData
context.Albums.Add(a)
context.SaveChanges()
Next
'ClientScript.RegisterStartupScript(Page.GetType(), "BulkAlbums", "$('#BulkRecords').modal();", True)
End If
Catch ex As Exception
End Try
End Sub
You are saving the file including the path, but then trying to access it with its filename only. The code is then trying to access that file from the running directory as a default instead of the directory that you saved the file in, which is why you are getting the "could not find file" error for the wrong path.
You should be able to fix this by specifying the full path when calling File.ReadAllLines
:
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)
User contributions licensed under CC BY-SA 3.0