title: SqlBulkCopy ColumnMapping error CSV to DataTable to SQL Server Table
body: <p>I am trying to bulk insert a CSV file into a SQL Server database.</p>
  
  <p>The process is <code>.CSV</code> file to <code>DataTable</code> to <code>SqlBulkCopy</code> to SQL Server.</p>
  
  <p>When I run this I get this error: </p>
  
  <blockquote>
    <p>The given ColumnMapping does not match up with any column in the source or destination</p>
  </blockquote>
  
  <p>When I directly import the CSV into SQL Server via Management Studio it works! So I think the problem is my data table conversion?</p>
  
  <p>Here is my code to go from <code>.CSV</code> to <code>DataTable</code>:</p>
  
  <pre><code>public DataTable CsvFileToDataTable(string filePath)
  {
      var csvData = new DataTable("Table1");
      using (var csvReader = new TextFieldParser(filePath))
      {
          csvReader.SetDelimiters(new string[] { "," });
          csvReader.HasFieldsEnclosedInQuotes = true;
          var readFields = csvReader.ReadFields();
  
          foreach (var dataColumn in readFields.Select(column =&gt; new DataColumn(column) {AllowDBNull = true }))
          {
              csvData.Columns.Add(dataColumn);
          }
          while (!csvReader.EndOfData)
          {
              var data = csvReader.ReadFields();
              for (var i = 0; i &lt; data.Length; i++)
              {
                  if (data[i] == "")
                  {
                      data[i] = null;
                  }
              }
              csvData.Rows.Add(data);
          }
      }
  
      return csvData;
  }
  </code></pre>
  
  <p>And here is the code for the bulk copy insert:</p>
  
  <pre><code>public void InsertData(DataTable table)
  {
      using (var transactionScope = new TransactionScope())
      {
          using (var sqlConnection = new SqlConnection(this.ConnectionString))
          {
              sqlConnection.Open();
  
              using (var sqlBulkCopy = new SqlBulkCopy(sqlConnection))
              {
                  sqlBulkCopy.DestinationTableName = table.TableName;
  
                  foreach (var column in table.Columns)
                  {
                      sqlBulkCopy.ColumnMappings.Add(column.ToString(), column.ToString());
                  }
  
                  sqlBulkCopy.WriteToServer(table);
              }
  
              transactionScope.Complete();
          }
      }
  }
  </code></pre>
  
  <p>Does anyone have any suggestions?</p>
  
  <p>Thanks</p>