views:

279

answers:

5

Hello,

I am reading a text file in C# and trying to save it to a SQL database. I am fine except I don't want the first line, which is the names of the columns, included in the import. What's the easiest way to exclude these?

The code is like this

while (textIn.Peek() != -1)
{
   string row = textIn.ReadLine();
   string[] columns = row.Split(' ');
   Product product = new Product();
   product.Column1 = columns[0];
   etc.....
   product.Save();
}

thanks

A: 

how are you importing the data? if you are looping in C# and inserting them one at a time, construct your loop to skip the first insert!

or just delete the first row inserted after they are there.

give more info, get more details...

KM
+2  A: 

If you are writing the code yourself to read in the file and then importing...why don't you just skip over the first line?

TheTXI
A: 

Pass a flag into the program (in case in future the first line is also data) that causes the program to skip the first line of text.

If it's the same column names as used in the database you could also parse it to grab the column names from that instead of hard-coding them too (assuming that's what you're doing currently :)).

As a final note, if you're using a MySQL database and you have command line access, you may want to look at the LOAD DATA LOCAL INFILE syntax which lets you import pretty arbitrarily defined CSV data.

workmad3
+1  A: 

Here's my suggestion:

string[] file_rows;
using(var reader=File.OpenText(filepath))
{
file_rows=reader.ReadToEnd().Split("\r\n");
reader.Close();
}

for(var i=1;i<file_rows.Length;i++)
{
var row=file_rows[i];
var cells=row.Split("\t");
....
}
Beatles1692
A: 

For future reference have a look at this awesome package: FileHelpers Library

I can't add links just yet but google should help, it's on sourceforge

It makes our lives here a little easier when people insist on using files as integration