combine two csv files in csharp

Here's a sample code snippet that combines two CSV files using C# and LINQ:

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

class Program
{
    static void Main(string[] args)
    {
        string filePath1 = @"C:\file1.csv";
        string filePath2 = @"C:\file2.csv";
        string outputFilePath = @"C:\output.csv";

        var data1 = File.ReadAllLines(filePath1)
                       .Skip(1)
                       .Select(x => x.Split(','))
                       .Select(x => new
                       {
                           Column1 = x[0],
                           Column2 = x[1],
                           Column3 = x[2],
                           // add columns as needed
                       });

        var data2 = File.ReadAllLines(filePath2)
                       .Skip(1)
                       .Select(x => x.Split(','))
                       .Select(x => new
                       {
                           Column1 = x[0],
                           Column2 = x[1],
                           Column3 = x[2],
                           // add columns as needed
                       });

        var combinedData = data1.Concat(data2);

        StreamWriter sw = new StreamWriter(outputFilePath);

        sw.WriteLine("Column1,Column2,Column3"); // add column names as needed

        foreach (var item in combinedData)
        {
            sw.WriteLine($"{item.Column1},{item.Column2},{item.Column3}");
        }

        sw.Close();

        Console.WriteLine("Files merged successfully.");
    }
}
1473 chars
51 lines

This code reads two CSV files, skips the header row, maps the data to an anonymous type using LINQ, concatenates the data, and writes the result to a new file. You can customize this code to suit your specific requirements.

gistlibby LogSnag