FileHelpers flat-file library

A while back, I started doing some work on an application that does a lot of flat-file writing -- specifically, fixed-width (positional) ASCII text files.  Now, this isn't really exciting stuff, but like COBOL, it still makes a lot of businesses go round, but doing flat-file manipulation by hand seemed like about seven kinds of crazy, so I started looking for a better solution.

I found a project called FileHelpers.  It's a utility library to help .Net applications read and write structured flat files. Most of the library lives in a core assembly with a number of "engine" classes that are used to drive I/O along with attributes that are used to decorate record classes in your application.

Your code uses these attributes to define records:

namespace FileHelpers.Tests
{

	[FixedLengthRecord(FixedMode.ExactLength)]
	internal class FixedRec1
	{	
		[FieldFixedLength(10)]
		[FieldAlign(AlignMode.Left)]
		[FieldNullValue("n/a")]
		[FieldTrim(TrimMode.Both)]
		public String String10Field1;

		[FieldFixedLength(10)]
		[FieldConverter(ConverterKind.Date)]
		public DateTime DateField2;

		[FieldFixedLength(12)]
		[FieldConverter(typeof(MoneyFieldConverter))]
		public decimal MoneyField3;
	}

}

To read or write files, then, one of the FileHelper engines works with the records you've defined to manipulate, format, and validate data:

var recs = new List<FixedRec1>();
recs.Add(new FixedRec1 { String10Field1 = "abc", DateField2 = DateTime.Today, MoneyField3 = 123.45M });  // show truncation of field 1
recs.Add(new FixedRec1 { String10Field1 = "abcdefghijklmnopqrstuvwxyz", DateField2 = DateTime.Today, MoneyField3 = 123.45M });  // show null translation of field 1
recs.Add(new FixedRec1 { DateField2 = DateTime.Today, MoneyField3 = 123.45M });  // show illegal value for field3
recs.Add(new FixedRec1 { String10Field1 = "abc", DateField2 = DateTime.Today, MoneyField3 = -0.00001M });
// To Write Use: engine.WriteFile("FileOut.txt", recs.ToArray());

You can extend FileHelpers by constructing your own custom attributes, such as converters to handle formats not natively provided by FileHelpers, but it's pretty handy to have source code for FileHelpers on-hand for debugging, because if you do any amount of heavy lifting with it, you'll end up wanting to walk through the code to see what's going on.

FileHelpers is open source software released under the LGPL. Source is available on SourceForge, but note that the released versions of code currently go up only to the 2.x release, dated 2007. If you're going to work with this library, you really want to go after the development source code, which is currently in a pre-release status for version 3.0, and compile the library on your own. You can find a subversion connection string on this Sourceforge page.