2

I am using FileHelpers library to write output files. Here is the sample code snippet:

 public class MyFileLayout
 {
    [FieldFixedLength(2)]
    private string prefix;

    [FieldFixedLength(12)]
    private string customerName;
 }

In my code flow, I would like to know each of those fields assigned length at run time, for eg: it is 12 for customerName.

Is there a way to get the values like above from FileHelpers library?

vijay
  • 635
  • 2
  • 13
  • 26
  • You want to get the values of the attributes? – Matten Aug 13 '13 at 07:46
  • Yes, But this is specific to FileHelpers library, I have already posted a question regarding getting attribute value, [http://stackoverflow.com/questions/18201971/how-do-i-get-the-custom-attribute-value-of-a-field/](http://stackoverflow.com/questions/18201971/how-do-i-get-the-custom-attribute-value-of-a-field/) – vijay Aug 13 '13 at 09:15

1 Answers1

1

I don't think you need the library te read the FieldAttribute properties.

        public class MyFileLayout
        {
            [FieldFixedLength(2)]
            public string prefix;

            [FieldFixedLength(12)]
            public string customerName;
        }




        Type type = typeof(MyFileLayout);
        FieldInfo fieldInfo = type.GetField("prefix");
        object[] attributes = fieldInfo.GetCustomAttributes(false);

        FieldFixedLengthAttribute attribute = (FieldFixedLengthAttribute)attributes.FirstOrDefault(item => item is FieldFixedLengthAttribute);

        if (attribute != null)
        {
            // read info
        }

I made a method for it:

    public bool TryGetFieldLength(Type type, string fieldName, out int length)
    {
        length = 0;

        FieldInfo fieldInfo = type.GetField(fieldName);

        if (fieldInfo == null)
            return false;

        object[] attributes = fieldInfo.GetCustomAttributes(false);

        FieldFixedLengthAttribute attribute = (FieldFixedLengthAttribute)attributes.FirstOrDefault(item => item is FieldFixedLengthAttribute);

        if (attribute == null)
            return false;

        length = attribute.Length;
        return true;
    }

Usage:

        int length;
        if (TryGetFieldLength(typeof(MyFileLayout), "prefix", out length))
        {
            Show(length);
        }

PS: the fields / properties must be public in order to read their attributes with reflection.

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
  • I specifically tagged this with FileHelpers, Getting the attribute value will work except in FileHelpers the Length property is decalred as internal, so I am unable to use this way. please refer my previous question [http://stackoverflow.com/questions/18201971/how-do-i-get-the-custom-attribute-value-of-a-field/] (http://stackoverflow.com/questions/18201971/how-do-i-get-the-custom-attribute-value-of-a-field/) – vijay Aug 13 '13 at 09:08