[HttpPost] public ActionResult Index(HttpPostedFileBase FileUpload) { DataTable dt = new DataTable(); if (FileUpload.ContentLength > 0) { string fileName = Path.GetFileName(FileUpload.FileName); string path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); try { FileUpload.SaveAs(path); dt = ProcessCSV(path); ViewData["Feedback"] = ProcessBulkCopy(dt); } catch (Exception ex) { ViewData["Feedback"] = ex.Message; } } else { ViewData["Feedback"] = "Please select a file"; } dt.Dispose(); return View("Index", ViewData["Feedback"]); } private static DataTable ProcessCSV(string fileName) { string Feedback = string.Empty; string line = string.Empty; string[] strArray; DataTable dt = new DataTable(); DataRow row; Regex r = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))"); StreamReader sr = new StreamReader(fileName); line = sr.ReadLine(); strArray = r.Split(line); Array.ForEach(strArray, s => dt.Columns.Add(new DataColumn())); while ((line = sr.ReadLine()) != null) { row = dt.NewRow(); row.ItemArray = r.Split(line); dt.Rows.Add(row); } sr.Dispose(); return dt; } private static String ProcessBulkCopy(DataTable dt) { string Feedback = string.Empty; string connString = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString; using (SqlConnection conn = new SqlConnection(connString)) { using (var copy = new SqlBulkCopy(conn)) { conn.Open(); copy.DestinationTableName = "BulkImportDetails"; copy.BatchSize = dt.Rows.Count; try { copy.WriteToServer(dt); Feedback = "Upload complete"; } catch (Exception ex) { Feedback = ex.Message; } } } return Feedback; }
@{ ViewBag.Title = "Index"; } <h2>Index</h2> @{ ViewBag.Title = "Home Page"; } <h2>CSV Bulk Upload</h2> @{ using (Html.BeginForm("", "", FormMethod.Post, new { enctype = "multipart/form-data" })) { <input type="file" name="FileUpload" /> <input type="submit" name="Submit" id="Submit" value="Upload" /> } } <p>@{ Html.Encode(ViewData["Feedback"]);} </p>
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)