Navigation

Saturday 7 September 2013

How to read CSV file using FileHelperEngine


In below program File.csv contains the all the info of students.

"ReadAllText" static method of  File class is used to read all the csv file

then resulted string is passed as a parameter to ReadString instance method 

of FileHelperEngine class which returns the Student type array.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using FileHelpers;
using System.Configuration;
namespace My_console_app
{

    class Program
    {
        static void Main(string[] args)
        {
            string fileData = File.ReadAllText("C:\\File.csv");
            FileHelperEngine engine = new FileHelperEngine(typeof(Student));
            engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;
            Student[] records = (Student[])engine.ReadString(fileData.Replace("\0", ""));
        }
    }

    [DelimitedRecord(",")]
    [IgnoreEmptyLines(true)]
    public class Student
    {
        [FieldQuoted('"', QuoteMode.OptionalForBoth)]
        public int Id;
        [FieldQuoted('"', QuoteMode.OptionalForBoth)]
        public string Name;
        [FieldQuoted('"', QuoteMode.OptionalForBoth)]
        public string Email;
    }

}


Here Student[] records contains all the students info as array.







No comments:

Post a Comment