Wednesday, August 5, 2009

How to read a excel/csv file using c#

Dot net provides different mechanism to read files. The problem occurs when you have large files to be read and processed. I had was wondering what difference a String and StringBuilder could make in the performance of manipulating a string record.

The real difference is too high while using String instead of StringBuilder and the system even reboots if the processing file size is too high.

public static string ReadCsvFile(string filePath)
StreamReader reader = null;
StringBuilder data = new StringBuilder();
string value = null;
using (reader = new StreamReader(filePath))
value = reader.ReadLine();
while (value!= null)
return data. ToString ();

The Method above uses StreamReader, which is a light weight .net class which could read the CSV or Excel file line by line without giving the system too much hurdle.

The StringBuilder uses less memory by allocating the same memory for the new text appended to it without creating more memory space like the string.

This set of code runs very fast and without any memory leakage.

No comments: