Trusa de scule 1- FileHelpers

Orice aplicatie are nevoie sa importe date. Cel mai simplu import de date este cel din fisiere de tip csv . Dar fiecare fisier CSV contine alte date –si trebuie de fiecare data sa facem maparea intre proprietatile clasei si pozitia in header. Mai mult, ce ar fi daca am vrea specificarea datei in doua moduri – yyyy-MM-dd si dd-MM-yyyy ?

Ca raspuns la aceasta exista FileHelpers – o librarie care va asigura importarea rapida a oricaror fisiere clar delimitate.

De exemplu sa presupunem ca vrem sa importam un fisier de GeoLocatii de la MaxMind, de forma

Copyright (c) 2007 MaxMind LLC.  All Rights Reserved.
locId,country,region,city,postalCode,latitude,longitude,metroCode,areaCode
1,”O1″,””,””,””,0.0000,0.0000,,
2,”AP”,””,””,””,35.0000,105.0000,,
3,”EU”,””,””,””,47.0000,8.0000,,

….

Trebuie sa ignoram la import primele 2 linii( copyright + header) si sa importam liniile urmatoare.

E simplu atunci: cream o clasa identica

 

[DelimitedRecord(“,”)]
    public class GeoLocation
    {
        public int Id { get; set; }
        public string CountryCode { get; set; } // TODO : create an enum Country and a mapper string->enum
        public string RegionCode { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }

        public float Latitude { get; set; }
        public float Longitude { get; set; }
        public string metroCode{ get; set; }
        public string areaCode { get; set; }
        public GeoLocation()
        {
           
        }
    }

 

iar de importat o facem cu urmatoarele rinduri

 

public IEnumerable<GeoLocation> ImportLocations(string csvFilePath, int HeaderLines=2)
        {
            DelimitedFileEngine engine = new DelimitedFileEngine(typeof (GeoLocation));
            engine.Options.IgnoreFirstLines = HeaderLines;           
            return engine.ReadFile(csvFilePath) as GeoLocation[];
        }

 

Ati observat ca are

engine.Options.IgnoreFirstLines = HeaderLines;

Ca sa ignoram, asa cum am spus, primele 2 linii.

Ceea ce mai avem de facut este sa obtinem datele:

var locations = (new CsvImporter()).ImportLocations(@”GeoLiteCity-Location.csv”);

Note:

Tutorial online la http://www.codeproject.com/Articles/12170/FileHelpers-v2-0-Delimited-CSV-or-Fixed-Data-Impor

Free source la http://www.filehelpers.com/

Leave a Reply

Your email address will not be published. Required fields are marked *