combine a csv in csharp

To combine multiple CSV files into a single file programatically using C#, you can follow these steps:

  1. Specify the path of the folder containing the CSV files and the path of the output file.
  2. Create a StreamWriter object and pass the output file path as a parameter.
  3. Loop through each CSV file in the folder.
  4. Open a StreamReader object for each CSV file.
  5. Read the CSV data and write it to the output file using the StreamWriter object.
  6. Close the StreamReader objects after reading all the data from the CSV files.
  7. Close the StreamWriter object after writing all the data to the output file.

Here's a sample code snippet that demonstrates these steps:

main.cs
string folderPath = @"C:\CSVFolder";
string outputFile = @"C:\CombinedCSV\output.csv";

using (StreamWriter writer = new StreamWriter(outputFile))
{
    foreach (string filePath in Directory.GetFiles(folderPath, "*.csv"))
    {
        using (StreamReader reader = new StreamReader(filePath))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                writer.WriteLine(line);
            }
        }
    }
}
469 chars
18 lines

Note that this code assumes that all the CSV files have the same structure (same number of columns in each file). Additionally, the columns in the output file will be ordered based on the order of the files in the folder (alphabetical order). You may need to modify the code based on your specific requirements.

related categories

gistlibby LogSnag