Click here to Skip to main content
15,880,796 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am working on a project and got small confusion. hope you can help me! I have one table that takes input from imported files. But when same file is again fetched from folder and about to save in table with changes in some field values it gives error ""violation of Primary key"" i solved it by using Ignore_Dup_key but after that it cannot saves the incoming row it just ignore that row.

ex : 1st file ==> 1,a,b,101
1st file again with different data ==> 1,f,d,102 where first field have primary key.

help me how can i solve this issue.

Here is code so far...

C#
public void ImportAllFilesOfFolder()//function declares methods to import// 
{ 
   try { 
    SqlConnection con = new SqlConnection(@"--constr---");
    string sourceDir = @"---  folderPath---";
    var IcsvFile = Directory.EnumerateFiles(sourceDir, "*.csv");

            foreach (string currentFile in IcsvFile)
            {
                StreamReader sr = new StreamReader(currentFile);
                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);
                    }
                }
                string q = "ALTER TABLE DeviceDetails REBUILD WITH (IGNORE_DUP_KEY=ON)";
                SqlCommand cm = new SqlCommand(q, con);
                con.Open();
                cm.ExecuteNonQuery();
                con.Close();

                SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
                bc.DestinationTableName = "DeviceDetails";
                bc.BatchSize = dt.Rows.Count;
                con.Open();
                bc.WriteToServer(dt);
                bc.Close();
                con.Close();                  
            }
Posted
Updated 24-Mar-15 1:58am
v4
Comments
Sinisa Hajnal 24-Mar-15 7:33am    
I've always used stored procedures so I cannot help you with the problem, sorry.

I can advise you to add try..finally block and close and dispose of the connection and command in finally block so they don't stay open in the case of exceptions
Joan Magnet 24-Mar-15 12:57pm    
If you want to allow duplicate keys, why don't remove the index?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900