Reputation: 113
I'm having trouble finding a nice way to parse out an object I have in C# in a fixed width format. The object has various properties. I found that the cleanest way to parse out the data itself was to use string formatting, so I need the lengths of each field. I currently have a static class set up like this:
public static class LENGTHS
{
public static int FIRST_NAME = 15;
public static int LAST_NAME = 25;
public static int ADDRESS1 = 25;
etc...
}
The lengths are then placed into an array. So like [15, 25, 25]
Then the data fields are placed into another array in the same order:
string[] info = { obj.Firstname, obj.LastName, obj.Address1, etc...};
I should also mention that every time the info string will be the exact same, and will not change overall unless I change only the order, in which case it will be changed every time.
They are then passed into a parser I made which finds the length of the field, and how long it should be from the length array, and inserts blank spaces accordingly using String.Format.
FixedWidthParser(info, Lengths);
The issue then is having to maintain the order for both of these arrays. In the event I have to change the order, I'd have to change the order of both arrays.
Am I going about this the wrong way? Is there a better way to do this? If so, can someone point me in the right direction?
Upvotes: 1
Views: 143
Reputation: 67223
This task isn't that hard to write from scratch. But there are a number of conveniences that can be added with a bit more work.
SoftCircuits.FixedWidthParser NuGet package will easily read a fixed width file and, optionally, automatically map the fields to class properties.
It also writes fixed-width files.
Upvotes: 0
Reputation: 4540
One possible solution would be to create a custom attribute for width and add it on the fields in the obj
type. Then somewhere store the field names in an array to provide the order for serialization. You can then use reflection to look up the fields by name, look up the length attribute on that field, and serialize [theorectically] the same way you're doing so now.
To get a field by name:
Type.GetField(string, BindingFlags)
https://msdn.microsoft.com/en-us/library/4ek9c21e(v=vs.110).aspx
To get the attributes of a field:
Getting the attributes of a field using reflection in C#
Upvotes: 3