Click here to Skip to main content
15,900,461 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I am reading a csv file into a sql table.

I need to skip the the first line which always starts with the string STR, eg "STR122", and the last line which is always END.

I was able ignore the substring "STR", but having problems with the substring "END".
I don't want "END" to be written into the DataTable

My code is as follows



DataTable dt = new DataTable();

     DataColumn dc = new DataColumn();

     bool endOfTransaction = false;

    string csvData = File.ReadAllText(filePath);
     dc.ColumnName = "Number";
     dt.Columns.Add(dc);

     foreach (string row in csvData.Split('\r'))
     {
         if (!string.IsNullOrEmpty(row) && row.Substring(0,3) != "STR")
         {
             if ((row.Substring(0, 3) == "END"))
             {
                 Console.WriteLine("End of file");
                 endOfTransaction = true;
             }
             else
             {
                 dt.Rows.Add(row);
             }
         }
     }

     SqlBulkCopy bc = new SqlBulkCopy(con,SqlBulkCopyOptions.TableLock, null);
     bc.DestinationTableName = "bulkAff_EmpNumbers";
     bc.WriteToServer(dt);
     bc.Close();


     cmd.CommandType = CommandType.StoredProcedure;
     cmd.CommandText = "[dbo].[chuck_doQAFF_C#]";
     cmd.Parameters.Add(new SqlParameter("@DebugMode", 1));
     cmd.CommandTimeout = 50000;

     SqlDataReader extractReader = cmd.ExecuteReader();

     WriteToFile file = new WriteToFile();
     file.parseResultSetToFile(extractReader);
Posted
Updated 26-Oct-15 3:07am
v3

1 solution

Quote:
if (row.row.Substring(0,3) != "END")
Shouldn't that be simply

if (row.Substring(0,3) != "END")
?
 
Share this answer
 
Comments
SiphoB 26-Oct-15 9:06am    
Sorry for that, that's a typing error. My actual code is if ((row.Substring(0, 3) == "END")).
But I am still getting the last line END in the dataTable
CPallini 26-Oct-15 9:10am    
Well, that's strange. Are you sure the case is the same? Are you sure there aren't spurious (invisible) characters in the string?
SiphoB 26-Oct-15 9:15am    
Yes, the CASE is definitely the same. at the end of every file, there is a "END"
CPallini 26-Oct-15 9:31am    
I suspect your last row begins this way
"\nEND"
(beacuse you splitted the string using just '\r').

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