To parse a comma-delimited file that has some fields enclosed in quotes:

using (DelimitedFieldParser parser = new DelimitedFieldParser("contacts.csv"))
{
	parser.SetDelimiters(',');
	parser.HasFieldsEnclosedInQuotes = true;
	
	while (!parser.EndOfFile)
	{
		try
		{
			// Reads the next record.
			TextFields fields = parser.ReadFields();
			
			contact = new ContactInfo();

			// Gets parsed data.
			contact.Name = fields.GetString(0);
			contact.Email = fields.GetString(1);
			contact.Birthday = fields.GetDateTime(2);

			contactList.Add(contact);
		}
		catch (MalformedLineException e)
		{
			// Handle exception here.
		}
	}
}

Last edited Jul 7, 2009 at 6:39 PM by mtricoli, version 2

Comments

No comments yet.