上传CSv文件asp。净

时间:2018-01-08 15:14:00

标签: asp.net vb.net csv

我试图将csv文件上传到我的数据库但是当我点击我的方法时它会给我错误:

  

NullRefereceExcetion对象未设置为对象的实例。

Dim csvPath As String = Server.MapPath (" ~ / Files / ") + Path.GetFileName (FileUpload1.PostedFile.FileName)

感谢您的帮助。

我的代码:

    'Upload and save the file
    Dim csvPath As String = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName)
    FileUpload1.SaveAs(csvPath)

    Dim dt As New DataTable()
    dt.Columns.AddRange(New DataColumn(2) {New DataColumn("CustomerId", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Country", GetType(String))})

    Dim csvData As String = File.ReadAllText(csvPath)
    For Each row As String In csvData.Split(ControlChars.Lf)
        If Not String.IsNullOrEmpty(row) Then
            dt.Rows.Add()
            Dim i As Integer = 0
            For Each cell As String In row.Split(","c)
                dt.Rows(dt.Rows.Count - 1)(i) = cell
                i += 1
            Next
        End If
    Next

    Dim constr As New Data.SqlClient.SqlConnection
    constr.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")

    Using sqlBulkCopy As New SqlBulkCopy(constr)
        'Set the database table name
        sqlBulkCopy.DestinationTableName = "dbo.Prueba"
        constr.Open()
        sqlBulkCopy.WriteToServer(dt)
        constr.Close()
    End Using

End Sub

0 个答案:

没有答案