We have a fixed output record format where all fields are pipe-delimited. The layout is fixed, but the required fields are not in sequence (and this cannot be changed because customers are using the existing layout). Can we use CSVHelper and the Index Attribute to write out blank fields, e.g [Index(1)], [Index(4)], [Index(7)] would yield something like:
"Field1Value,,,Field2Value,,,Field3Value"?
We may eventually add the missing fields, but will have to consider this in a phased manner (because of customer implications), but want to be able to create the minimal output record format with the required field values.
We are working with .Net Core 2.2/C# for our efforts.
I looked at several nuget and other libraries that support decorating properties with data attributes like [Column(xx)] and [FieldOrder(xx)], but settled on CSVHelper because it seems robust and widely used.
public class Person
{
[Index(1)]
public string Name { get; set; }
[Index(4)]
public short Age { get; set; }
[Index(7)]
public string StreetAddress { get; set; }
}
static void Main(string[] args)
{
var records = new List<Person>
{
new Person { Name = "Jon Doe", Age = 100, StreetAddress = "123 Market Place" }
};
using (var writer = new StreamWriter("C:\\Projects\\CsvHelperDemo\\file.csv"))
using (var csv = new CsvWriter(writer))
{
csv.WriteRecords(records);
}
}
Expected:
Name,,,Age,,,StreetAddress
Jon Doe,,,100,,,123 Market Place
Actual:
Name,Age,StreetAddress
Jon Doe,100,123 Market Place