我正在使用FileHelper将记录写入平面文件。
这些记录的前20个字段是固定的,如果值为空,将填充空格。
尽管最后4个字段是可选的,但如果它们全部为空,则这些位置不应用空格填充。但是FileHelper继续用空格填充这些位置。

是否可以使用FileHelper来实现?

[FixedLengthRecord(FixedMode.AllowVariableLength)]
public class MyReport
{
    [FieldFixedLength(2)]
    public string field1;

    [FieldFixedLength(10)]
    public string field2;
    ...
    [FieldFixedLength(96)]
    [FieldOptional]
    public string field32;

    [FieldFixedLength(96)]
    [FieldOptional]
    public string field33;

    [FieldFixedLength(96)]
    [FieldOptional]
    public string field34;

    [FieldFixedLength(96)]
    [FieldOptional]
    public string field35;
}

最佳答案

您可以删除AfterWriteRecord event中的所有多余分隔符。

这是一个工作示例:

[DelimitedRecord(",")]
public partial class Person
{
    public string FirstName;
    public string LastName;
    [FieldOptional]
    public string Optional1;
    [FieldOptional]
    public string Optional2;
    [FieldOptional]
    public string Optional3;
}

class Program
{
    private static void Main(string[] args)
    {
        var engine = new FileHelperEngine<Person>();
        engine.AfterWriteRecord += engine_AfterWriteRecord;
        var export = engine.WriteString(
                     new Person[] {
                       new Person() { FirstName = "Joe", LastName = "Bloggs" }
                     });
        Assert.AreEqual("Joe,Bloggs" + Environment.NewLine, export);
    }

    static void engine_AfterWriteRecord(EngineBase engine, AfterWriteEventArgs<Person> e)
    {
        // trim trailing empty separators
        e.RecordLine = e.RecordLine.TrimEnd(',');
    }
}

10-02 01:56