inserting into SQL via sqlbulk

sqlbulkcopy

Question

hallo i have this sniped code like this:

 public static void Put_CSVtoSQL_Adhesion()
    {
        bool IsFirst = true;      
        DataTable dt = new DataTable();
        string line = null;
        int i = 0;

        try
        {
            string fileName = Path.Combine(HttpContext.Current.Server.MapPath(UploadDirectory), TheFileName);

            using (StreamReader sr = File.OpenText(fileName))
            {
                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());
                            }
                            i++;
                        }
                        DataRow row = dt.NewRow();
                        row.ItemArray = data;

                        // Pour enlever la tete 
                        if (!IsFirst) dt.Rows.Add(row);
                        IsFirst = false;
                    }
                }
            }

            using (var connectionWrapper = new Connexion())
            {
                var connectedConnection = connectionWrapper.GetConnected();
                using (SqlBulkCopy copy = new SqlBulkCopy(connectionWrapper.conn))
                {
                    int CountColl = dt.Columns.Count;

                    copy.ColumnMappings.Add(0, 1);
                    copy.ColumnMappings.Add(1, 2);
                    copy.ColumnMappings.Add(2, 3);
                    copy.ColumnMappings.Add(3, 4);
                    copy.ColumnMappings.Add(4, 5);


                    copy.DestinationTableName = "cotisation";
                    copy.WriteToServer(dt);
                }
            }
        }
        catch (Exception excThrown)
        {
            throw new Exception(excThrown.Message);
        }
    }

this code work well, but now i have more than 60 column, should i type manualy from 1 to 60 column or there are another methode ?

 copy.ColumnMappings.Add(0, 1);
                    copy.ColumnMappings.Add(1, 2);
                    copy.ColumnMappings.Add(2, 3);
                    copy.ColumnMappings.Add(3, 4);
                    copy.ColumnMappings.Add(4, 5);

...until 60 column ?

the column is all the same i just shifted 1 column, because the first one is autoincremented column as an ID

Accepted Answer

Write a loop?

for (int i = 0; i < dt.Columns.Count - 1; i++)
{
    copy.ColumnMappings.Add(i, i + 1);
}



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why