Reputation: 53
I'm looking for the fastest way to read data from a CSV file. I tried doing this two different ways.
Method #1: Reading all of the lines from the CSV file into an array an then iterating the array:
String[] csv = File.ReadAllLines(@"E:\be.csv");
for (int i = 0; i < csv.Length; i++)
{
tx.Text = csv[i];
tx.Refresh();
}
Method #2*: Using StreamReader
:
StreamReader sr = new StreamReader(new FileStream(@"E:\be.csv");
while (!sr.EndOfStream)
{
string seg = sr.ReadLine();
tx.Text = sr.ReadLine();
tx.Refresh();
}
Using StreamReader
seems to be a lot faster. Is there an even faster method to import data from a CSV file?
Upvotes: 2
Views: 934
Reputation: 74375
Sebastien Loren's Fast CSV Reader on CodeProject is probably the way to go.
It implements IDataReader
and acts mostly like a StreamReader.
Highly recommended.
Upvotes: 3
Reputation: 9089
I must suggest CsvHelper which can be found in NuGet. Having used it for the first time yesterday, it will now be my go to solution.
http://www.nuget.org/packages/CsvHelper/
For your actual question of what's faster, I would probably say just doing File.ReadAllLines(...)
, but it would be best for you to actually try and set up a test to do both options several hundred times and see which one took the longest.
Also, do not forget to dispose your StreamReader
. Go ahead and wrap that in a using
statement so everything gets closed/disposed probably.
Upvotes: 3