Use a TextFieldParser to read fixed-width data in C#

[TextFieldParser]

This example uses a TextFieldParser object to load fixed-width data from a file that contains names and addresses. Each field has a fixed width. Some records also have ZIP+4 format ZIP codes (for example, 08109-2120) and the program should discard the +4 part of the data. Finally the data file contains some blank lines in the middle and at the end, and the program should ignore them.


The following text shows the file.

Barbara             Roberts             2044 22nd St                  San Pablo           CA24806
Ken                 Carson              565 Atlanta South Pkwy        Atlanta             GA10349
Horatio             Crunch              565 Atlanta South Pkwy        Atlanta             GA70349-5958
Patricia            Reichardt           3655 Millbranch Rd            Memphis             TN18116-4817

Aloysius            Snuffleupagus       9252 N 49th St                Pennsauken          NJ08109-2120
Edgar               Mallory             3655 Millbranch Rd            Memphis             TN38116
Jonas               Grumby              2832 Amerson Way              Ellenwood           GA30294
Roy                 Hinkley             29426 Christiana Way          Laguna Niguel       CA92677


The example program uses the following code to read and display the data.

// Load the data.
private void Form1_Load(object sender, EventArgs e)
{
    // Open a TextFieldParser using these delimiters.
    using (TextFieldParser parser =
        FileSystem.OpenTextFieldParser("Names.txt"))
    {
        // Set the field widths.
        parser.TextFieldType = FieldType.FixedWidth;
        parser.FieldWidths = new int[] { 20, 20, 30, 20, 2, 5 };

        // Process the file's lines.
        while (!parser.EndOfData)
        {
            try
            {
                string[] fields = parser.ReadFields();
                ListViewItem item = lvwPeople.Items.Add(fields[0]);
                for (int i = 1; i <= 5; i++)
                {
                    item.SubItems.Add(fields[i]);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

    lvwPeople.AutoResizeColumns(
        ColumnHeaderAutoResizeStyle.HeaderSize);
}

The code starts by creating a TextFieldParser. It sets the parser’s TextFieldType property to FixedWidth and its FieldWidths property to an array holding the fields’ widths in characters.

Note that the TextFieldParser class and the FileSystem class used here are in the Microsoft.VisualBasic.FileIO namespace. The program includes the following using directive to make using the namespace easier. I also added a reference to the Microsoft.VisualBasic library at design time.

// Add a reference to Microsoft.VisualBasic.
using Microsoft.VisualBasic.FileIO;

After creating the parser, the program loops while the parser’s EndOfData property returns false. The EndOfData property automatically changes to true after the parser reads the last record in the data file even if the file ends with some blank lines, so the parser won’t get confused.

As long as EndOfData is false, the program calls the parser’s ReadFields method to read the next record’s fields into an array of strings. The program must then interpret the fields appropriately. In this example the program simply displays the first 6 fields in a ListView control, the first one as a ListView item and the others as sub-items.

See also Use a TextFieldParser to read delimited data in C#.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in classes, database, files, parsing and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

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