Mai Hu Na

Mai Hu Na

  • NA
  • 86
  • 131k

chk next line while read current line using streamreader c#

Jul 9 2013 4:37 PM
hi friend,
This is my code. plz see the attach sample file to load.i am missing the comment ;chennai while flushing bulk after count 5 that why i need to check next line content while current line read.hope understand.
if file are not available

File content
----------------------------
atul,salunke
amol,salunke
anil,salunke
;dandegaon
amar,salunke
;bhoom
akash,salunke
;chennai
pappu,salunke
----------------------------

int counter = 0;
  int cnt = 0;
  string line = "";
  SqlConnection con = new SqlConnection("Data Source=atul-pc;Initial Catalog=TestDB;Integrated Security=True");
  SqlBulkCopy bulkCopy = new SqlBulkCopy(con, SqlBulkCopyOptions.TableLock
  | SqlBulkCopyOptions.FireTriggers
  | SqlBulkCopyOptions.UseInternalTransaction, null);
  con.Open();
  bulkCopy.BatchSize = 5;
  bulkCopy.BulkCopyTimeout = 3000;

  string[] sField = null;
  DataRow row;
 


  System.IO.StreamReader file = new System.IO.StreamReader("H:\\sample file.txt");
  // userTable();


  DataTable table = new DataTable();
  DataColumn col1 = new DataColumn("iID"); table.Columns.Add("iID", System.Type.GetType("System.Int32"));
  DataColumn col2 = new DataColumn("vchFirstName"); table.Columns.Add("vchFirstName", System.Type.GetType("System.String"));
  DataColumn col3 = new DataColumn("vchLastName"); table.Columns.Add("vchLastName", System.Type.GetType("System.String"));
  DataColumn col4 = new DataColumn("Comment"); table.Columns.Add("Comment", System.Type.GetType("System.String"));

  bulkCopy.DestinationTableName = "userDetails";
  bulkCopy.ColumnMappings.Add("iID", "iID");
  bulkCopy.ColumnMappings.Add("vchFirstName", "vchFirstName");
  bulkCopy.ColumnMappings.Add("vchLastName", "vchLastName");
  bulkCopy.ColumnMappings.Add("Comment", "Comment");


  int priv = 0;

 
  while ((line = file.ReadLine()) != null)
  {
  int columnCount =0 ;
  char[] cDelim = new char[] { ',' };
  sField = line.Split(cDelim);
  if (line.Contains(","))
  {
  counter++;
  priv = counter;
  row = table.NewRow();
  row["iID"] = counter;
  foreach (string s in sField)
  {
  columnCount++;
  row[columnCount] = s.Trim();
  }
  table.Rows.Add(row);

  }
  if (line.Contains(";"))
  {
 
  DataRow[] result = table.Select("iID="+priv+"");
  result[0]["Comment"] = line.Trim();
 
  }
 
  if (Math.Floor((double)counter / 5) != Math.Floor((double)(counter - 1) / 5))
  {
  bulkCopy.WriteToServer(table);
  table.Clear();
  }
  cnt++;
  }


Answers (1)