title: Import a CSV file to SQL with C# and asp.net
body: <p>I'm working with SQL Server 2014. One of the features of my web app is to upload CSV files, and import the data into a table (called <code>TF</code>) in my database (called <code>TMPA</code>).</p>
  
  <p>I have no idea how to do this.</p>
  
  <pre><code>string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload2.PostedFile.FileName);
  FileUpload1.SaveAs(excelPath);
  
  SqlConnection con = new SqlConnection(@"Data Source=SAMSUNG-PC\SQLEXPRESS;Initial Catalog=TMPA;Persist Security Info=True");
  
  StreamReader sr = new StreamReader(excelPath);
  string line = sr.ReadLine();
  string[] value = line.Split(',');
  
  DataTable dt = new DataTable();
  DataRow row;
  
  foreach (string dc in value)
  {
      dt.Columns.Add(new DataColumn(dc));
  }
  
  while (!sr.EndOfStream)
  {
     value = sr.ReadLine().Split(',');
  
     if (value.Length == dt.Columns.Count)
     {
        row = dt.NewRow();
        row.ItemArray = value;
        dt.Rows.Add(row);
     }
  }
  
  SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
  bc.DestinationTableName = "TF";
  bc.BatchSize = dt.Rows.Count;
  
  con.Open();
  bc.WriteToServer(dt);
  bc.Close();
  
  con.Close();
  </code></pre>
  
  <p>I tried this code, but it wouldn't work.</p>
  
  <p>PS : <code>TF</code> has more columns than what the CSV file : some of the columns are computed and should be calculated automatically after each insert ..</p>
  
  <p>Here is the canvas of my CSV file : 4 columns :</p>
  
  <pre><code> IdProduit,Mois,Reel,Budget
  </code></pre>
  
  <p><code>IdProduit</code> is a string, <code>Mois</code> is a date, <code>Reel</code> and <code>Budget</code> are floats.</p>
  
  <p>On the other hand, my SQL Server table looks like this :</p>
  
  <pre><code>  |IdProduit|Mois|Reel|Budget|ReelPreviousMois|VarReelBudget|VarReelPrvM|...
    |---------|----|----|------|----------------|-------------|-----------|-----
  </code></pre>
  
  <p>All the other columns should either be null or automatically calculated.</p>
  
  <p>Help me !</p>