简体   繁体   中英

Is there a way to suppress a property when writing out a file with FileHelpers?

Is there a way to suppress a property when writing out a file with FileHelpers?

Say I have an object:

[DelimitedRecord(",")]
public class MyClass
{
    public int Field1 { get; set; }
    public string Field2 { get; set; }
    public string Field3 { get; set; }
    public string Field4 { get; set; }
    public string Field5 { get; set; }
}

I want to write out a csv but I want to omit Field3 (regardless if it's populated or not).

Ex.
Output would be: Field1,Field2,Field4,Field5
Is there an attribute that I can use in FileHelpers to suppress writing out a file?

From the documentation here and here you would use the FieldValueDiscarded attribute. Here is the full blurb:

Use the FieldValueDiscarded attribute for fields that you don't use.

If your record class has some fields that are not used, the library will discard the value of fields marked by this attribute

As a workaround, you can use an AfterWrite event to remove the last delimiter. Something like this:

[DelimitedRecord(",")]
class Product : INotifyWrite
{
    [FieldQuoted(QuoteMode.AlwaysQuoted)]
    public string Name;
    [FieldQuoted(QuoteMode.AlwaysQuoted)]
    public string Description;
    [FieldOptional]
    public string Size;

    public void BeforeWrite(BeforeWriteEventArgs e)
    {
        // prevent output of [FieldOptional] Size field
        Size = null;
    }

    public void AfterWrite(AfterWriteEventArgs e)
    {
        // remove last "delimiter"
        e.RecordLine = e.RecordLine.Remove(e.RecordLine.Length - 1, 1);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var engine = new FileHelperEngine<Product>();
        var products = new Product[] { new Product() { Name = "Product", Description = "Details", Size = "Large"} };
        var productRecords = engine.WriteString(products);
        try
        {
            // Make sure Size field is not part of the output
            Assert.AreEqual(@"""Product"",""Details""" + Environment.NewLine, productRecords);
            Console.WriteLine("All tests pass");
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred");
            Console.WriteLine(ex);
        }

        Console.ReadKey();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM