I have a statement like:
string[] lines = System.IO.File.ReadAllLines(file);
foreach (string line in lines)
{
...
}
which causes me error as there is a header in the underlying .csv file. I want to skip this row, but when I use:
string [] lines = System.IO.File.ReadLines(file).Skip(1).ToArray();
yields me that String
cannot use Skip(1)
. The same thing when I try to use:
string[] lines = System.IO.File.ReadAllLines(file);
lines = lines.Skip(1).ToArray();
yields me the same error.
Does anyone have any idea? Can I adjust the Foreach
loop to become a For
loop where I dismiss the first row?
Regards,
EDIT
The code I use as of now is:
string[] lines = System.IO.File.ReadAllLines(file);
lines = lines.Skip(1).ToArray();
foreach (string line in lines)
{
var cols = line.Split(';');
if (cols.Length == 1)
continue;
DataRow dr = tbl.NewRow();
dr[0] = file;
for (int cIndex = 1; cIndex + 1 < tbl.Columns.Count; cIndex++)
{
dr[cIndex + 1] = cols[cIndex];
}
}
System.Text.StringBuilder b = new System.Text.StringBuilder();
foreach (System.Data.DataRow r in tbl.Rows)
{
foreach (System.Data.DataColumn c in tbl.Columns)
{
b.Append(c.ColumnName.ToString() + ":" + r[c.ColumnName].ToString());
}
}
MessageBox.Show(b.ToString());
return tbl;
here the b.ToString() returns Nothing (as in NULL). Earlier when I used the GetAllLines() it returned:
fileName:fileNameStore:storeQuantity:quantityfileName:fileNameStore:1000Quantity:30
and it goes on like that.
My ideas are that perhaps I've made it so that I only imported one big long string, so when I skip the first line, it gets NULL.
But this is my first C# code ever, so I'm having some difficulties figuring this out.
there is no problem with your current algorithm:
string[] lines = System.IO.File.ReadAllLines(file);
lines = lines.Skip(1).ToArray();
just ensure you import the namespace below.
using System.Linq;
I would use the File.ReadLines()
instead of the File.ReadAllLines()
.Because it is lazy loading the file. U'd rather not use the .ToArray()
or the .ToList()
as it would persist the whole file into the memory.
This will stream the data.
foreach(var line in File.ReadLines(file).Skip(1))
{
}
Will do the job...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With