I have a csv file that I need to read one line at a time and fill .net objects from it (first line header).
Now, I know I can do it via
ReadLine
and then assign the object properties but I was wondering if there's any shorter way of doing it.
I tried using LINQ but that reads all the lines at ones File.ReadAllLines("C:\\....csv").Skip(1)...
Please advice. Thanks.
Asked
Active
Viewed 59 times
0

Amar
- 303
- 1
- 3
- 19
-
please refer this url http://stackoverflow.com/questions/1941392/are-there-any-csv-readers-writer-libraries-in-c – Sanjay Radadiya Aug 17 '16 at 04:23
-
Replace `ReadAllLines` with [`ReadLines`](https://msdn.microsoft.com/en-us/library/dd383503(v=vs.110).aspx) – Ivan Stoev Aug 17 '16 at 07:26
1 Answers
1
yep Ivan say it, use ReadLines()
for reading header and data in one access you can use the old school Enumerator:
static void Main(string[] args)
{
var enumerator = File.ReadLines("foo.csv").GetEnumerator();
enumerator.MoveNext();
string headerLine = enumerator.Current; // null if file empty
while (enumerator.MoveNext())
{
string dataLine = enumerator.Current;
}
}
or after the headline you can convert the Enumerator to IEnumerable<> back:
static IEnumerable<T> AsEnumerable<T>(IEnumerator<T> enumerator)
{
while (enumerator.MoveNext()) yield return enumerator.Current;
}
and replace the while loop with var query = AsEnumerable(enumerator);

MaxKlaxx
- 713
- 7
- 9