For one of my customers, I have to develop applications that communicate with each other via fixed-width files. In other words, they have developed a file format that is "generic" to a lot of operations. If I write a new utility, it is expected that the utility will be able to read, write, and parse this generic file. The file is fixed-width, with each field taking up a "hard-coded' number of bytes.
Of course I'll write a reusable class to handle the file i/o. My question is, what is the best approach to handling fixed-width fields?
Each field will have to be a property. All data is essentially string data. I could define a string per field, but how do I force the strings to be a specific length? All strings will be right-padded with spaces...
For example, there is a 20-byte "account number" field. It starts at byte 56 in the record, and always takes up 20-bytes in the record. If I pass in a 12-byte value, the string should hold 12 bytes followed by 8 spaces.
In C#, you cannot "DIM" a string to a pre-defined length, can you?
Should I use StringBuilder to dynamically build the record, appending the fields/string, then appending spaces equal to the required length of the field minus the actual length of the string?
Is there an elegant way to store the field names/lengths?
I'm envisioning a class called "GenericIO", with the fields as properties:
GenericIO.account = "123456789ABC";
The "setter" for that property would look of the required length of "account", perhaps stored in a 2-dimensional array. It would then pad-out the string, adding the requisite number of spaces, and would return the final formatted string. If the string is too long, the class would generate an error.
Is this a good approach? Other suggestions?