Almost every project I have worked on, reading/writing data from/to files in a fixed-length or <insert your favorite separator here> separated format. Recently, I’ve used SSIS to import large datasets from fixed-length files into a database. However, sometimes you also need to access these files from inside your code (in my case: for testing purposes) and although writing the code to this is not particularly difficult, it is not the most fun way to spend your time. A few minutes quality-time with google and voila: FileHelpers for .NET!

For example, if you want to read the data from the following file:

Amos|Tori|Little Earthquakes|19920225
Amos|Tori|Under The Pink|19940201
Gabriel|Peter|Passion|19890606

you just define the following class to hold the records

    [DelimitedRecord("|")]
    class AlbumRecord
    { 
        public string name;
        public string firstName;
        public string album;
        [FieldConverter(ConverterKind.Date, "yyyyMMdd")]
        public Date releaseDate;
}

Reading the file into an array of AlbumRecord objects is now as simple as:

    FileHelperEngine<albumrecord> engine = new FileHelperEngine<albumrecord>();
    AlbumRecord[] recordsFromFile = engine.ReadFile("albums.txt");

Fixed length files can be processed in a similar way…

Advertisements