BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Input / Output
.NET 2.0+

Reading Fixed-Width Data

Fixed-width formats provide an alternative to comma-separated values (CSV) when text files must be used to transfer information between systems. When reading such files, field data is extracted according to its horizontal position in the text.

Fixed-Width Data

Fixed-width data files are useful when you need to transfer information between two systems that cannot communicate directly and that share no other common file format. They provide an alternative to comma-separated values (CSV) files for storing tabular data. Rather than delimiting fields in the text file with a special symbol, such as a comma, the fields in a fixed-width file are identified by their column position. This does create wasted space, meaning that fixed-width files are usually larger in size than their CSV equivalents. However, they can be more human-readable.

An example fixed-width format is shown below. You can see that the data for the forename, surname, age and salary of the listed employees are aligned to specific column positions. We'll be using this file in the sample code so copy and paste it into a text file and save it. Note that that lines include trailing spaces, ensuring every row is the same length. You should copy these spaces.

Andrew              Green               25 26000     
Ben                 Brown               32 28500     
Celia               Black               29 28000     
Steve               Pink                41 52000     

Reading a Fixed-Width File

You can read the data from a fixed-width format file using the same class as you would for a CSV file. This is the TextFieldParser class, which is found in the Microsoft.VisualBasic.FileIO namespace. I've described the use of this class in an earlier article so I won't repeat the information here. We'll just look at how to configure it for working with fixed-width, rather than delimited, text files.

Start by adding a reference to the Microsoft.VisualBasic assembly and including the following using directive:

using Microsoft.VisualBasic.FileIO;

You can create a TextFieldParser in the same manner as described in the earlier article, by passing the path to the target file to the class's constructor. The sample below includes this within a using statement to ensure that the object is correctly disposed and the file resource is released as soon as possible. NB: You should change the path in the sample according to the location in which you saved the test file.

To configure the object for use with fixed-width files we need to change the value held in the TextFieldType property. By default this is set to the Delimited value from the FieldType enumeration. We need to change this to FixedWidth. We also need to specify the widths of each of the fields in our data rows. This is done by providing an integer array of widths to the SetFieldWidths method. The widths define the columns in the data source from left to right.

Once we've configured our TextFieldParser we can loop through the rows of the file until the EndOfData property becomes true. Each time we read a line of data we are given an array of strings according to the column widths we specified, as shown below:

static void Main()
{
    using (TextFieldParser tfp = new TextFieldParser(@"c:\temp\test.txt"))
    {
        tfp.TextFieldType = FieldType.FixedWidth;
        tfp.SetFieldWidths(new int[] { 20, 20, 3, 10 });
        while (!tfp.EndOfData)
        {
            string[] fields = tfp.ReadFields();
            ShowEmployee(fields);
        }
    }
}

private static void ShowEmployee(string[] fields)
{
    Console.WriteLine("Name:\t{0} {1}", fields[0].Trim(), fields[1].Trim());
    Console.WriteLine("Age:\t{0}", fields[2].Trim());
    Console.WriteLine("Salary:\t£{0}", fields[3].Trim());
    Console.WriteLine();
}

/* OUTPUT

Name:   Andrew Green
Age:    25
Salary: £26000

Name:   Ben Brown
Age:    32
Salary: £28500

Name:   Celia Black
Age:    29
Salary: £28000

Name:   Steve Pink
Age:    41
Salary: £52000

*/
22 December 2012