c# - How do I get the assigned fixed length of the field from FileHelpers library? -
i using filehelpers library write output files. here sample code snippet:
public class myfilelayout { [fieldfixedlength(2)] private string prefix; [fieldfixedlength(12)] private string customername; }
in code flow, know each of fields assigned length @ run time, eg: 12 customername.
is there way values above filehelpers library?
i don't think need library te read 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 fieldfixedlengthattribute); if (attribute != null) { // read info }
i made method 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 fieldfixedlengthattribute); if (attribute == null) return false; length = attribute.length; return true; }
usage:
int length; if (trygetfieldlength(typeof(myfilelayout), "prefix", out length)) { show(length); }
ps: fields / properties must public in order read attributes reflection.
Comments
Post a Comment