Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

Read delimited record containing delimited field with varying length with FileHelpers in C#?

I am using MultiRecordEngine() to read a delimited .txt file with no header and different type of records. The first two character of any record is the identifier which I am using to identify the type of the record.

The problem I am encountering is that in RecordB(see sample model below), I have a field which contains multiple values delimited with the same delimiter being used in the file. And also the field length is not fixed, it's length depends on the number of values in it. for e.g. FieldB-0000-1111-2222-3333-FieldD where 0000-1111-2222-3333 will need to be read in FieldC.

Note: FieldB contains an integer which denoted the amount of values that will be present in FieldC

I am using MultiRecordEngine() to read the file and map the records to my models for the different type of records.

A sample that looks close to what I have:

1 sample model

[DelimitedRecord("-")]
public class RecordB
{
    public string RecordIdentifier { get; set; }
    public string FieldA { get; set; }
    public string FieldB { get; set; } <-- contains a value determining the amount of values in FieldC
    public string FieldC { get; set; } <-- read delimited values to this field [delimiter: -]
    public string FieldD { get; set; }
    public string FieldE { get; set; }
}

Reading the file using MultiRecordEngine

new MultiRecordEngine(RecordSelector,
    typeof(RecordA),
    typeof(RecordB),
    typeof(RecordC),
);

My RecordSelector looks similar to:

switch (recordType)
{
    case "XX":
        return typeof(RecordA);
    case "XY":
        return typeof(RecordB);
    default:
        return null;
}

I did try using a combination of [DelimitedRecord("-")] and [FixedLengthRecord(FixedMode.AllowLessChars)] on the model as well as [FieldDelimiter("~")] on the field but no luck. Is there anything I'm missing? Please advise.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found a workaround. I'm using the model below to read only the record I know that contains the delimited field and splitting the values later and getting them by index.

[FixedLengthRecord(FixedMode.ExactLength)]
public class RecordB
{
    [FieldFixedLength(100)]
    public string WholeRecord { get; set; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...