Click here to Skip to main content
13,087,566 members (96,493 online)
Click here to Skip to main content
Add your own
alternative version


31 bookmarked
Posted 28 Oct 2006

Handling Fixed-width Flat Files with .NET Custom Attributes

, 28 Oct 2006
Rate this:
Please Sign up or sign in to vote.
Handling Fixed width flat files with .NET custom attributes


This article shows how to handle flat files containing fixed width datafields, using .NET custom attributes. It doesn't explain custom attributes, because I think there has already been enough written on that subject.


How many times did you have to exchange data coming from or going to another environment like a mainframe? Many projects I have worked on needed to import or export datafiles in a fixed width format. The code handling these files must be flexible enough to handle changes in the file format, that's why I created the code described in this article.

Using the Code

Suppose your code needs to import a file containing customers with the following layout :

Id        PIC(9)
Code    PIC(1)
Name   PIC(20)

To read the data from the file, you create a customer class that must derive from a provided base class called StringLayoutUtility. This base class has two important methods : Parse() and ToString(). These two methods will iterate over each property of (your) the (derived) class, having a StringLayoutAttribute defined. With the position information it will find in the StringLayoutAttribute, it will know how to parse or build the string. So on each property, you assign a StringLayoutAttribute, together with two arguments: the begin and end position of the property in the input-string as shown below:

[StringLayoutAttribute(0, 8)]
public string Id
   get { return _Id; }
   set { _Id = value; }

The Id field starts at position 0 and ends at position 8, meaning the Id field is 9 characters long.

The StringLayoutUtility class also has a virtual method IsValid() that can be used to do some business validation after the parsing.
public override bool IsValid()
   // add your validation logic here
   return (!String.IsNullOrEmpty(this.Id) && !String.IsNullOrEmpty(this.Name));


The first code sample provided shows how a string is parsed, and is later compared with the result of the ToString() method:

// this simulates input from a FlatFileReader
string fileLineIn = "123456789ADepoorter Stephan WhateverStreet 456AB1000 Brussels" +
Customer customer = new Customer();
string fileLineOut = customer.ToString();
Console.WriteLine("customer.Parse() " + 
                         ((fileLineIn == fileLineOut.TrimEnd()) ? "==" : "!=") + 
                         " customer.ToString() !" );

The second code sample shows the reading of a file customers.txt, using the FlatFileReader:

// Sample using the FlatFileReader:
FlatFileReader file = new FlatFileReader("customers.txt", Encoding.GetEncoding(
while (file.ParseLine())

Base Class

public void Parse(string input)
  if(!String.IsNullOrEmpty(input ) )
    foreach (PropertyInfo property in GetType().GetProperties())
      foreach (Attribute attribute in property.GetCustomAttributes(true))
        StringLayoutAttribute stringLayoutAttribute = attribute as StringLayoutAttribute;
        if (null != stringLayoutAttribute)
          string tmp = string.Empty;
          if (stringLayoutAttribute.StartPosition <= input.Length - 1)
            tmp = input.Substring(stringLayoutAttribute.StartPosition, 
                stringLayoutAttribute.EndPosition - stringLayoutAttribute.StartPosition +
                1), input.Length - stringLayoutAttribute.StartPosition));
          switch (_trimInput)
            case TrimInputMode.Trim :
               tmp = tmp.Trim();
            case TrimInputMode.TrimStart:
               tmp = tmp.TrimStart();
            case TrimInputMode.TrimEnd:
               tmp = tmp.TrimEnd();
          property.SetValue(this, tmp, null);

public override string ToString()
  string result = string.Empty;
  foreach (PropertyInfo property in GetType().GetProperties())
    foreach (Attribute attribute in property.GetCustomAttributes(false))
      StringLayoutAttribute stringLayoutAttribute = attribute as StringLayoutAttribute;
      if (null != stringLayoutAttribute)
        string propertyValue = (string)property.GetValue(this, null);
        if (stringLayoutAttribute.StartPosition > 0 && result.Length < 
          result = result.PadRight(stringLayoutAttribute.StartPosition, _paddingChar);
        string left = string.Empty;
        string right = string.Empty;
        if (stringLayoutAttribute.StartPosition > 0)
          left = result.Substring(0, stringLayoutAttribute.StartPosition);
        if (result.Length > stringLayoutAttribute.EndPosition + 1)
          right = result.Substring(stringLayoutAttribute.EndPosition + 1);
        if (propertyValue.Length < stringLayoutAttribute.EndPosition - 
            stringLayoutAttribute.StartPosition + 1)
           propertyValue = propertyValue.PadRight(stringLayoutAttribute.EndPosition - 
            stringLayoutAttribute.StartPosition + 1, _paddingChar);
        result = left + propertyValue + right;
  return result;



The sample shown was kept very basic on purpose. Often you will need to parse a part of the input data fields, and then depending on what you have read in the first part, parse the rest of the line differently. This can be handled easily, by using base classes to read the first part, and pass these to a factory that will instantiate an appropriate class that will parse the remaining fields of the input line.


I hope to have shown a simple and flexible implementation to read and create files containing fixed width fields, using .NET custom attributes.


  • October, 2006: Initial version


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Stephan Depoorter
Web Developer
Belgium Belgium
Stephan works as a .NET solution archtect at Euricom, one of Belgiums leading .NET companies.

You may also be interested in...

Comments and Discussions

GeneralGood article Pin
amitraipopli26-May-10 16:49
memberamitraipopli26-May-10 16:49 
GeneralRe: Good article Pin
Stephan Depoorter26-May-10 21:10
memberStephan Depoorter26-May-10 21:10 
GeneralRe: Good article Pin
amitraipopli27-May-10 7:49
memberamitraipopli27-May-10 7:49 
GeneralGreat article!!! Pin
Member 6632195-Jan-10 5:53
memberMember 6632195-Jan-10 5:53 
Questionlooking for the code? Pin
mikec7-Dec-07 8:59
membermikec7-Dec-07 8:59 
AnswerRe: looking for the code? Pin
Stephan Depoorter22-Apr-08 10:26
memberStephan Depoorter22-Apr-08 10:26 
QuestionLooking for the code? Pin
mikec7-Dec-07 8:47
membermikec7-Dec-07 8:47 
GeneralExcellent Article, need one now for a comma delimited file! Pin
v1rich12-Jul-07 8:17
memberv1rich12-Jul-07 8:17 
AnswerRe: Excellent Article, need one now for a comma delimited file! Pin
Stephan Depoorter13-Jul-07 11:53
memberStephan Depoorter13-Jul-07 11:53 
GeneralNice Utility Pin
wvh29-Oct-06 22:06
memberwvh29-Oct-06 22:06 
GeneralNice Article Pin
Marcos Meli29-Oct-06 12:17
memberMarcos Meli29-Oct-06 12:17 
GeneralGreat Article Pin
Phillip M. Hoff28-Oct-06 20:55
memberPhillip M. Hoff28-Oct-06 20:55 
GeneralRe: Great Article Pin
Stephan Depoorter29-Oct-06 9:25
memberStephan Depoorter29-Oct-06 9:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170813.1 | Last Updated 29 Oct 2006
Article Copyright 2006 by Stephan Depoorter
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid