Code Project

Link Unit

Monday, May 25, 2009

FileHelpers : Strong type your flat file

We were working on a project, where it required to read a pipe separated values from the file. This is how we were doing it earlier

 

try

{

          StreamReader sr = new StreamReader(lstrFilePath);

          while ((lstrReadLine = sr.ReadLine()) != null)

          {

                    string[] lstrsplit = lstrReadLine.Split(new Char[] { '|' });

                    string lstrCOMP_NAME = lstrsplit[1];

                    string lstrFULL_NAME = lstrsplit[2];

                    string lstrFATHER_NAME = lstrsplit[3];

                    string lstrDESIGNATION = lstrsplit[4];

 

                    rowInsert["COMP_NAME"] = lstrCOMP_NAME;

                    rowInsert["FULL_NAME"] = lstrFULL_NAME;

                    rowInsert["FATHER_NAME"] = lstrFATHER_NAME;

                    rowInsert["DESIGNATION"] = lstrDESIGNATION;

 

                    dtANX.Rows.Add(rowInsert);

 

          }

}

catch(Exception e)

{

 

// Error Logging

 

}

finally

{

// Will always be called

 if (sr != null) // This check can be ignored though

                sr.Close();

}               

 

We started looking for a class (Helper Class), which can import/export flat files into DataTable/Array.

Then came across this useful dll FileHelpers. We converted our previous code to the one written below

 

Step 1) Created a class in .cs file and specify deliminator , which was | (pipe) in our case

[DelimitedRecord("|")]  

 public class Anxeure  

 {  

     public string COMP_NAME;  

       

     public string FULL_NAME;  

  

     public string FATHER_NAME;  

  

     public string DESIGNATION;  

    

     //..... and other columns in the sequence they will come in file.

  

 }  

 

 

 Step 2) Create an instance of FileHelperEngine and read the file.

 

 FileHelperEngine engine = new FileHelperEngine(typeof(Anxeure));  

  

 // To Read Use:  

 Anxeure[] res = engine.ReadFile("FileIn.txt") as Anxeure[];  

 

//We could also export the data thus created after doing some manipulation

engine.WriteFile("FileOut.txt", res);  

 

It is amazing how by writing two statements we could achieve a strongly typed output. Great

 

Hope it helps

Jatinder

 

 

2 comments:

Marcos Meli said...

Hi there

U can use also the Generic version of the engine :)

FileHelperEngine<Anxeure> engine = new FileHelperEngine<Anxeure>();

To avoid casting
// To Read Use:
Anxeure[] res = engine.ReadFile("FileIn.txt");

Best Regards

Jatinder Singh said...

Thanks for your input Marcos.It would be better if you could guide how delimented files with character other than [,] be parsed .
We can read csv file directly into dataset by using OleDB . Anything similar for PSV etc.