使用FileHelpers写出文件时是否有办法抑制属性?
说我有一个对象:
[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; }
}
我想写出一个csv,但我想省略Field3(无论是否填充)。
实施例。
输出为:Field1,Field2,Field4,Field5
是否有可以在FileHelpers中使用的属性来禁止写出文件?
答案 0 :(得分:0)
从文档here和here中,您将使用FieldValueDiscarded属性。这是完整的模糊:
对您不使用的字段使用FieldValueDiscarded属性。
如果您的记录类有一些未使用的字段,则库将丢弃此属性标记的字段的值
答案 1 :(得分:0)
作为一种变通方法,您可以使用AfterWrite
事件删除最后一个分隔符。像这样:
[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();
}
}