Search code examples
c#sql.netcsvint32

Input string was not in a correct format in c#, int value is not in correct format


Following is the code for it:

protected void Upload(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                //Upload and save the file
                string csvPath = Server.MapPath("~/App_Data/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
                FileUpload1.SaveAs(csvPath);


            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[7] 
            {
            new DataColumn("pataintno", typeof(int)),
            new DataColumn("Firstname", typeof(string)),
            new DataColumn("Lastname",typeof(string)),
            new DataColumn("Age", typeof(int)),
            new DataColumn("Address", typeof(string)),
            new DataColumn("Email", typeof(string)),
            new DataColumn("Phno", typeof(int)),});


            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["cnstr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(consString))
            {
                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                {
                    //Set the database table name
                    sqlBulkCopy.DestinationTableName = "Pataint";
                    con.Open();
                    sqlBulkCopy.WriteToServer(dt);
                    con.Close();
                    Array.ForEach(Directory.GetFiles((Server.MapPath("~/App_Data/"))), File.Delete);
                }
            }
        }
        else
        {
            Label1.Text = "PlZ TRY AGAIN";
        }
    }

Solution

  • I checked the code and it seems fine. I suggest you to check the csv file and make sure there are no headers for any columns.