combine two csv files if the headers match in csharp

The following code snippet demonstrates how to combine two CSV files if their headers match in C# using LINQ:

main.cs
using System;
using System.Linq;
using System.IO;

class Program {
    static void Main(string[] args) {
 
        var file1 = @"C:\path\to\file1.csv";
        var file2 = @"C:\path\to\file2.csv";
        var output = @"C:\path\to\output.csv";
        var separator = ',';
        var hasHeader = true;

        // Read files into arrays of strings
        var lines1 = File.ReadAllLines(file1);
        var lines2 = File.ReadAllLines(file2);

        // Split header and data for each file
        var header1 = lines1.First().Split(separator);
        var data1 = lines1.Skip(1);

        var header2 = lines2.First().Split(separator);
        var data2 = lines2.Skip(1);

        // Verify that headers match
        if (!header1.SequenceEqual(header2)) {
            Console.WriteLine("Headers do not match");
            return;
        }

        // Combine headers and data, and write to output file
        var result = new[] { header1 }.Concat(data1).Concat(data2);
        File.WriteAllLines(output, result.Select(row => string.Join(separator, row)));

        Console.WriteLine("Files combined successfully");
    }
}
1129 chars
38 lines

Explanation:

  • The input CSV file paths are stored in file1 and file2, and the output CSV file path is stored in output.
  • The variable separator is used to split input CSV rows into columns.
  • hasHeader is a boolean flag indicating whether an input CSV file has a header row.
  • The contents of the input CSV files are read into memory as arrays of strings using the File.ReadAllLines() method.
  • The header row and data rows are separated for each input CSV file.
  • The SequenceEqual() method is used to verify that the headers of both files match.
  • The header row and data rows from both files are concatenated into a single array using the Concat() method.
  • The output file is written using the File.WriteAllLines() method.

gistlibby LogSnag