Sonali Avhad

Sonali Avhad

  • NA
  • 234
  • 39.2k

while Importing csv file to sql table it gives error

Sep 29 2020 5:03 AM
While importing csv file to sql it gives following error-
 String was not recognized as a valid DateTime.Couldn't store <15/09/2020> in TXNDATE Column. Expected type is DateTime. 
 
my CS file code is as follow- 
 
 
 
string csvPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(csvPath);
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[4] {
new DataColumn("SRNO", typeof(Int32)),
new DataColumn("BANKNAME",typeof(string)),
new DataColumn("NETAMOUNT",typeof(Decimal)),
new DataColumn("TXNDATE",typeof(DateTime))
});
string csvData = File.ReadAllText(csvPath);
foreach (string row in csvData.Split('\n'))
{
if (!string.IsNullOrEmpty(row))
{
dt.Rows.Add();
int i = 0;
foreach (string cell in row.Split(','))
{
dt.Rows[dt.Rows.Count - 1][i] = cell;
i++;
}
}
}
string consString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name.
sqlBulkCopy.DestinationTableName = "dbo.TableName";
con.Open();
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}

Answers (1)