3

I am using the FileHelpers library to create a txt document which contains a list of employees, the document needs to be created with fixed size fields, I need to add a header and footer with a different structure than the body, for example in the header and footer it is necessary to write the total of records and the current date. How could I add these two sections?

public class Employee
{
   [FieldFixedLength(10)]
   public int Secuencial;

   //[FieldFixedLength(10)]
   //[FieldOptional]
   //public int Total;

   //[FieldFixedLength(10)]
   //[FieldConverter(ConverterKind.Date, "yyyy-MM-dd")]
   //[FieldOptional]
   //public DateTime CurrentDate;

   [FieldFixedLength(50)]
   public string Names;

   [FieldFixedLength(5)]
   public int Age;
}

The final file should look like this

  32022-09-26
1 Andres Valle 35
2 Sandra Calle 28
3 Pepe Granja  30
  32022-09-26

Code to write file:

public static void WriteFile(string outputPath, DataTable dt)
{
 var report = new FileHelperEngine<Employee>();
 var lstEmpl = new List<Employee>();
 Employee empl;

 //Employee header = new Employee();
 //header.Total = 3;
 //header.CurrentDate = DateTime.Today;

 foreach (DataRow dr in dt.Rows)
 {
   empl = new Employee();
   empl.Names = dr["names"].ToString();
   empl.Age = int.Parse(dr["age"].ToString());
   lstEmpl.Add(empl);
 }
 report.WriteFile(outputPath, lstEmpl);
//report.AppendToFile(outputPath, header);
}
Andrés
  • 43
  • 5
  • Can you post some example code what have your tried so far? Btw you can open the file before you edit with your library and append the header/footer etc. – IamK Sep 26 '22 at 21:36
  • I edited my question, everything that is as a comment is what I have tried, I have tried to add the header fields as optional, however the error that occurs is that the spaces when generating the file are respected, for example in the body displays blanks for Total and CurrentDate fields – Andrés Sep 26 '22 at 22:10

1 Answers1

0

You can wrap your employee object in a class, which has the header field an employee list and a footer field

public class EmployeeWrapper
{
    public string Header { get; set; }
    public List<Employee> Employees { get; set; }
    public string Footer { get; set; }
}
IamK
  • 2,753
  • 5
  • 30
  • 39