Search code examples
c#csvfilehelpers

How do I append to a CSV file using Filehelpers with multiple record types that have distinct headers?


As the question says, using the FileHelpers library I am attempting to generate a CSV file along side a report file. The report file may have different (but finite) inputs/data structures and hence my CSV generation method is not explicitly typed. The CSV contains all of the report data as well as the report's header information. For my headers, I am using the class object properties because they are descriptive enough for my end use purpose.

My relevant code snippet is below:

            // File location, where the .csv goes and gets stored.
            string filePath = Path.Combine(destPath, fileName);

            // First, write report header details based on header list
            Type type = DetermineListType(headerValues);
            var headerEngine = new FileHelperEngine(type);
            headerEngine.HeaderText = headerEngine.GetFileHeader();
            headerEngine.WriteFile(filePath, (IEnumerable<object>)headerValues);

            // Next, append the report data below the report header data.
            type = DetermineListType(reportData);
            var reportDataEngine = new FileHelperEngine(type);
            reportDataEngine.HeaderText = reportDataEngine.GetFileHeader();
            reportDataEngine.AppendToFile(filePath, (IEnumerable<object>)reportData);

When this is executed, the CSV is successfully generated however the .AppendToFile() method does not add the reportDataEngine.HeaderText. From the documentation I do not see this functionality to .AppendToFile() and I am wondering if anyone has a known work-around for this or a suggestion how to output the headers of two different class objects in a single CSV file using FileHelpers.

The desired output would look something like this however in a single CSV file (This would be a contiguous CSV obviously; not tables)

Report_Name Operator Timestamp
Access Report User1 14:50:12 28 Dec 2020
UserID Login_Time Logout_Time
User4 09:33:23 10:45:34
User2 11:32:11 11:44:11
User4 15:14:22 16:31:09
User1 18:55:32 19:10:10

I have looked also at the MultiRecordEngine in FileHelpers and while I think this may be helpful, I cannot figure out based on the examples how to actually write a multirecord CSV file in the required fashion I have above; if it is possible at all.

Thank you!


Solution

  • The best way is to merge the columns and make one big table then make your classes match the columns you need to separate them out when reading. CSV only allows for the first row to define the column names and that is optional based on your use case. Look at CSVHelper https://joshclose.github.io/CsvHelper/ it has a lot of built-in features with lots of examples. Let me know if you need additional help.