Skip to content

Instantly share code, notes, and snippets.

@renato04
Created June 17, 2021 15:33
Show Gist options
  • Save renato04/e5bdb4267f8254487e52a576dc870a81 to your computer and use it in GitHub Desktop.
Save renato04/e5bdb4267f8254487e52a576dc870a81 to your computer and use it in GitHub Desktop.
How to transform a fixed length string file structure to any object
public class LineDefinitionAttribute : Attribute
{
public LineDefinitionAttribute(int size, int startIndex, string format = "")
{
Size = size;
StartIndex = startIndex;
}
public int Size { get; set; }
public int StartIndex { get; set; }
public string Format { get; set; }
}
public class Item
{
[LineDefinition(size: 1, startIndex: 0)]
public int Id { get; set; }
[LineDefinition(size: 50, startIndex: 1)]
public string Name { get; set; }
}
public static class StringExtensions
{
public static T ToObject<T>(this string fixedLengthString) where T : new()
{
var properties = typeof(T).GetProperties().Where(p => p.GetCustomAttributes(typeof(LineDefinitionAttribute), false).Count() > 0);
if (!properties.Any())
return default;
var obj = Activator.CreateInstance<T>();
foreach (var property in properties)
{
var attribute = property.GetCustomAttributes(false).FirstOrDefault(p => p.GetType() == typeof(LineDefinitionAttribute));
if (attribute == null)
continue;
var lineDefinitionAttribute = (LineDefinitionAttribute)attribute;
var stringValue = fixedLengthString.Substring(lineDefinitionAttribute.StartIndex, lineDefinitionAttribute.Size);
if (property.PropertyType == typeof(int))
property.SetValue(obj, int.Parse(stringValue));
else if (property.PropertyType == typeof(long))
property.SetValue(obj, long.Parse(stringValue));
else if (property.PropertyType == typeof(decimal))
property.SetValue(obj, decimal.Parse(stringValue));
else if (property.PropertyType == typeof(DateTime))
property.SetValue(obj, DateTime.ParseExact(stringValue, lineDefinitionAttribute.Format, CultureInfo.InvariantCulture));
else
property.SetValue(obj, stringValue);
}
return obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment