Thursday, November 27, 2008

Using the VB TextFieldParser in C#

Sometimes you run across some hidden gems in the framework. One of these is the TextFieldParser class in the Microsoft.VisualBasic namespace. The TextFieldParser allows you to read and parse delimited files by specifying the positions as an array or by specifying the delimiters.    I know that a lot of C# developers would cringe at the thought of referencing a library from that other language, but given the functionality and the fact that this method requires no RegEx or xslt makes it a great solution.

Here's a quick sample that parses a position delimited file:

   1: public void ParsePositionalFile(string path)


   2:         {


   3:           


   4:             using (TextFieldParser parser = new TextFieldParser(path))


   5:             {


   6:                 parser.TextFieldType = FieldType.FixedWidth;


   7:                 int[] fields = { 9, 18, 36, 2, 25, 1, 1, 1, 8 };


   8:                 parser.SetFieldWidths(fields);


   9:                 string[] currentRow = new string[8];


  10:                 while (!parser.EndOfData)


  11:                 {


  12:                     currentRow = parser.ReadFields();


  13:                     foreach (string s in currentRow)


  14:                     {


  15:                         Console.WriteLine(s +'\t');


  16:                     }


  17:                 }


  18:  


  19:             }


No comments: