当位置仅在运行时已知时,是否可以解析/读取固定位置布局平面文件?我看到有一个关于SO的问题与使用“运行时记录”的类似内容有关,但这涉及读取分隔文件 - Dynamically create a Fixed Length text file with FileHelpers
我的目的是将具有不同固定长度格式的固定长度平面文件解析为通用格式,并在运行时加载固定长度格式。 FileHelpers倾向于使用属性来定义字段的位置和长度,这是事先定义的,但我想在运行时指定它。
感谢。
答案 0 :(得分:2)
这就是我所做的。希望它可以帮助你。
private void ImportFiles()
{
DataTable dt = GetFixedFileSpecsFromDB(layoutName); //Get the specs
//Create Dynamic class based on Specs above
FixedLengthClassBuilder cb = GetSpecClass(dt);
//Create FileHelpers engine instance
FileHelperEngine engine = new FileHelperEngine(cb.CreateRecordClass());
//Read file data into Data table
DataTable dtImportData = engine.ReadFileAsDT(ImportFilePath);
}
//Method to create the Fixed lentgh dynamic class
public static FixedLengthClassBuilder GetSpecClass(DataTable dt)
{
string className = "ImportSpecifications";
FixedLengthClassBuilder cb = new FixedLengthClassBuilder(className);
//Loop thru each field and prepare the class
foreach (DataRow dr in dt.Rows)
{
int fieldLength = Convert.ToInt32(dr.Field<decimal>("FieldLength"));
switch (dr["FieldDataType"].ToString())
{
case "String":
cb.AddField(dr.Field<string>("FieldName"), fieldLength, typeof(string));
cb.LastField.FieldNullValue = string.Empty;
cb.LastField.TrimMode = FileHelpers.TrimMode.Both;
break;
case "Date":
cb.AddField(dr.Field<string>("FieldName"), fieldLength, typeof(DateTime));
cb.LastField.FieldNullValue = string.Empty;
break;
case "Integer":
cb.AddField(dr.Field<string>("FieldName"), fieldLength, typeof(int?));
//cb.LastField.FieldNullValue = 0;
break;
case "Long Integer":
cb.AddField(dr.Field<string>("FieldName"), fieldLength, typeof(long));
cb.LastField.FieldNullValue = 0;
break;
case "Decimal":
cb.AddField(dr.Field<string>("FieldName"), fieldLength, typeof(decimal?));
//cb.LastField.FieldNullValue = 0;
break;
default:
break;
}
}
return cb;
}