ASP.NET – Import csv with accented characters

Posted by | January 08, 2012 | ASP.NET, Web Development | One Comment
CSV

For one of my project I needed to import data from csv to the database in bulk. First I wrote my own CSV parser and it worked fine for simple scenarios except strings with commas’ or contains single/double quotes. Than googled for open source libraries for parsing csv files. I found a few good libraries. Than I tried csvreader at codeproject for reading CSV files which is very good. This parser handles everything such as parsing CSVs correctly so you don’t have to worry about problems like these. It is very easy to use and the data can be returned via a DataTable.

public IEnumerable<Person>; ImportCSV(Stream stream)
{
	var persons = new List<Person>;();
	var streamReader = new StreamReader(stream, Encoding.Default);
	var hasHeaders = false;
	using (CsvReader csvReader = new CsvReader(streamReader, hasHeaders))
	{
		csvReader.SkipEmptyLines = true;
		while (csvReader.ReadNextRecord())
		{
			var firstName = csvReader[0];
			var lastName = csvReader[1];
			var email = csvReader[2];

			persons.Add(new Person()
			{
				FirstName = firstName,
				LastName = lastName,
				Email = email
			});
		}
	}
	return persons;
}

Library source:
http://www.codeproject.com/KB/database/CsvReader.aspx
 

avatar

About Farid

Creative web developer/designer, big fan of HTML5, CSS3 and client-side development. Software developer at Allegra Strategies London.

  • Amedeo Margarese

    Very helpful, thank you