1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
public ActionResult Importcsv()
{
return View();
}
[HttpPost]
public ActionResult Importcsv(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"] = "Sélectionnez un fichier";
}
dt.Dispose();
return View("Importcsv", ViewData["Feedback"]);
}
private static String ProcessBulkCopy(DataTable dt)
{
string Feedback = string.Empty;
string connString = ConfigurationManager.ConnectionStrings["BagatellesDBContext"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (var copy = new SqlBulkCopy(conn))
{
copy.DestinationTableName = "Articles";
copy.BatchSize = dt.Rows.Count;
try
{
copy.WriteToServer(dt);
Feedback = "Chargement effectué";
}
catch (Exception ex)
{
Feedback = ex.Message;
}
}
return Feedback;
} |