Link to home
Start Free TrialLog in
Avatar of darthvader747
darthvader747

asked on

Read Flat File and insert each line to database

The task is to read a flat file which is pipe delimited (first row has column names). Insert all data fields into the database (MS SQL; using sqlclient). The code is in c#. I have here the code to read line and split fields. Please help me include the sqlparemeters in the foreach line loop so each line can be inserted into the table.
I haven't been able to assign values of the parameters inside the loop while reading each line. Help me out. Thanks
string strLine;
string[] strArray;
char[] charArray = new char[] { '|' };
FileStream aFile = new FileStream(pathToFile, FileMode.Open);
StreamReader sr = new StreamReader(aFile);
strLine = sr.ReadLine();
string sqlcmd=@"Insert into table value1, value2, value3, value4 values (@value1,@value2,@value3,@value4)"; 
strArray = strLine.Split(charArray);
//read column names
for (int x = 0; x <= strArray.GetUpperBound(0); x++)
  {
     strArray[x].Trim();
  }
strLine = sr.ReadLine();
while (strLine != null)
  {
     strArray = strLine.Split(charArray);
     for (int i = 0; i <= strArray.GetUpperBound(0); i++)
     {
       strArray[i].Trim();
       // here add code to add SqlParameters 
       // cmd.Parameters.Add(new SqlParameter("@value1", null));
       //cmd.Parameters["value1].Value = strArray[1];
     }
      strLine = sr.ReadLine();
      sqlcmd.ExecuteNonQuery();
   }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Miguel Oz
Miguel Oz
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of darthvader747
darthvader747

ASKER

This method works. Just implemented and tested it. Thank You so much!