Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Handling Empty Values in SqlBulkCopy

Handling Empty Values in SqlBulkCopy

Handling Empty Values in SqlBulkCopy

Hello, I have a FileImport class which is using SqlBulkCopy method. It works great if all the values in the .txt file are populated, but if there are any empty values it fails.

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;

public class FileImport
public static void Import(string savePath)
DataTable dt = new DataTable();
string line = null;
int i = 0;

using (StreamReader sr = File.OpenText(savePath))
while ((line = sr.ReadLine()) != null)
string[] data = line.Split('|');
if (data.Length > 0)
if (i == 0)
foreach (var item in data)
dt.Columns.Add(new DataColumn());
DataRow row = dt.NewRow();
for (int j = 0; j < data.Length; j++)
if (!string.IsNullOrEmpty(data[j]))
row[j] = System.Convert.ChangeType(data[i], row.Table.Columns[i].DataType);
row.ItemArray = data;

using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TESTConnectionString"].ToString()))
using (SqlBulkCopy copy = new SqlBulkCopy(conn))
copy.ColumnMappings.Add(0, 0); //BATCH_TYPE_ID
copy.ColumnMappings.Add(1, 1); //LOAD_DATE (throws exception if empty)
copy.ColumnMappings.Add(2, 2); //VENDOR_ID
copy.ColumnMappings.Add(3, 3); //TAB_TYPE_ID
copy.ColumnMappings.Add(4, 4); //TYPE_1
copy.ColumnMappings.Add(5, 5); //TYPE_2

copy.DestinationTableName = "TestSubmission";

Any help would be greatly appreciated.


RE: Handling Empty Values in SqlBulkCopy

In the constructor, try adding the SqlBulkCopyOptions.KeepNulls option.

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close