/// <summary> /// eg:04abcd /// data=abcd ,herder=len(abcd)=04 /// </summary> /// <param name="headerLength">add length for eatch data row</param> /// <returns></returns> public string ToFixedLengthString(int headerLength) { int length = 0; StringBuilder sb = new StringBuilder(); foreach (var pi in this.GetType().GetProperties()) { FixedLengthAttribute attribute = FixedLengthHelper.GetCustomAttribute <FixedLengthAttribute>(pi); if (attribute != null && attribute.Length > 0) { if (attribute.Type == FixedLengthType.A) { sb.Append(HandleFixedString(pi.GetValue(this, null), attribute.Length)); } else { sb.Append(HandleFixedNumber(pi.GetValue(this, null), attribute.Length)); } length += attribute.Length; } } if (headerLength > 0) { sb.Insert(0, HandleFixedNumber(length.ToString(), headerLength)); } return(sb.ToString()); }
public static T FromFixedLengthString <T>(string input, int headerLength) { T obj = Activator.CreateInstance <T>(); string value = ""; int startIndex = 0; if (headerLength > 0) { startIndex = headerLength; } StringBuilder sb = new StringBuilder(); foreach (var pi in obj.GetType().GetProperties()) { FixedLengthAttribute attribute = FixedLengthHelper.GetCustomAttribute <FixedLengthAttribute>(pi); if (attribute != null && attribute.Length > 0) { if (input.Length <= startIndex) { break; } else if (input.Length > startIndex && input.Length < startIndex + attribute.Length) { //value = input.Substring(startIndex); value = SubstringWide(input, startIndex); } else { //value = input.Substring(startIndex, attribute.Length); value = SubstringWide(input, startIndex, attribute.Length); } pi.SetValue(obj, value, null); startIndex += attribute.Length; } } return(obj); }