I'm setting up a back office for our admin team on our website and looking to allow the user to update the database via a csv file import setup.
My code looks like this:
protected void Upload(object sender, EventArgs e)
{
//Upload and save the file
string csvPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(csvPath);
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[13] { new DataColumn("ID", typeof(int)),
new DataColumn("ZooplaURL", typeof(string)),
new DataColumn("Branch",typeof(string)),
new DataColumn("HouseNumber",typeof(string)),
new DataColumn("PropAddress",typeof(string)),
new DataColumn("Town",typeof(string)),
new DataColumn("County",typeof(string)),
new DataColumn("Postcode",typeof(string)),
new DataColumn("Price",typeof(string)),
new DataColumn("PropType",typeof(string)),
new DataColumn("Beds",typeof(string)),
new DataColumn("PropStatus",typeof(string)),
new DataColumn("Weeks",typeof(string)) });
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["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.Zoopla";
con.Open();
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}
}
}
}
The error it returns when uploading is as follows:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IndexOutOfRangeException: Cannot find column 13.
Source Error:
Line 72: foreach (string cell in row.Split(','))
Line 73: {
Line 74: dt.Rows[dt.Rows.Count - 1][i] = cell;
Line 75: i++;
Line 76: }
The CSV file has 13 columns being imported and the database also has 13 columns.