I have created sample code to know the route cause of this issue.
So we can write code like this.
Sample code:-
#region bulkCopy
if (MyConnection.State == ConnectionState.Closed) MyConnection.Open();
DataTable dataTableName = GetDataTabletFromCSVFile(filenamestr1);
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(MyConnection))
{
bulkCopy.DestinationTableName = "Destination_TBL_My_Name_Temp";
try
{
bulkCopy.WriteToServer(dataTableName);
}
catch (Exception ex)
{
WriteErrorLog_Debug("My_FileExtractService " + ex.Message.ToString() + " " + ex.StackTrace.ToString() + " / " + RefNo, "testTimer_Elapsed1");
string message = "";
if (ex.Message.Contains("Received an invalid column length from the bcp client for colid"))
{
string pattern = @"\d+";
Match match = Regex.Match(ex.Message.ToString(), pattern);
var index = Convert.ToInt32(match.Value) - 1;
FieldInfo fi = typeof(SqlBulkCopy).GetField("_sortedColumnMappings", BindingFlags.NonPublic | BindingFlags.Instance);
var sortedColumns = fi.GetValue(bulkCopy);
var items = (Object[])sortedColumns.GetType().GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sortedColumns);
FieldInfo itemdata = items[index].GetType().GetField("_metadata", BindingFlags.NonPublic | BindingFlags.Instance);
var metadata = itemdata.GetValue(items[index]);
var column = metadata.GetType().GetField("column", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);
var length = metadata.GetType().GetField("length", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);
message = (String.Format("Column: {0} contains data with a length greater than: {1}", column, length));
}
string aa = message;
WriteErrorLog_Debug("My_FileExtractService Detailed Exception " + message.ToString() + " " + ex.StackTrace.ToString() + " / " + RefNo, "testTimer_Elapsed1");
}
}
#endregion