Dynamically create a Fixed Length text file with FileHelpers

谁都会走 提交于 2019-12-11 12:29:45

问题


FileHelpers supports a feature called "RunTime Records" which lets you read a Fixed length text file into a DataTable when you don't know the layout until runtime.

Is it possible to use FileHelpers to export a Fixed length file at runtime in the same manner?


回答1:


Here's a working sample for export using a DataTable as source.

public static class DataTableExtensions
{
    public static List<object> DataTableToList(this DataTable table, Type type)
    {
        List<object> list = new List<object>();
        foreach (var row in table.AsEnumerable())
        {
            object obj = Activator.CreateInstance(type);
            foreach (var field in obj.GetType().GetFields())
            {
                FieldInfo fieldInfo = obj.GetType().GetField(field.Name);
                fieldInfo.SetValue(obj, Convert.ChangeType(row[field.Name], fieldInfo.FieldType));
            }
            list.Add(obj);
        }

        return list;
    }
}

class Program
{
    private static void Main(string[] args)
    {
        var cb = new FixedLengthClassBuilder("Customer");

        cb.AddField("BirthDate", 8, typeof(DateTime));
        cb.LastField.Converter.Kind = ConverterKind.Date;
        cb.LastField.Converter.Arg1 = "ddMMyyyy";
        cb.LastField.FieldNullValue = DateTime.Now;

        cb.AddField("Name", 3, typeof(string));

        cb.AddField("Age", 3, typeof(int));
        cb.LastField.TrimMode = TrimMode.Both;

        Type recordClass = cb.CreateRecordClass();

        var dataTable = new DataTable("Customer");
        dataTable.Columns.Add("BirthDate", typeof(DateTime));
        dataTable.Columns.Add("Name", typeof(string));
        dataTable.Columns.Add("Age", typeof(int));

        dataTable.Rows.Add(new DateTime(1972, 8, 14), "Joe", 42);
        dataTable.Rows.Add(new DateTime(1971, 9, 15), "Tine", 43);

        var list = dataTable.DataTableToList(recordClass);

        var engine = new FileHelperEngine(recordClass);
        engine.WriteFile(filename, list);

        Console.ReadKey();
    }
}


来源:https://stackoverflow.com/questions/31251643/dynamically-create-a-fixed-length-text-file-with-filehelpers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!