Sujeet Raman

Sujeet Raman

  • 870
  • 927
  • 355.3k

how to merge multiple text file and convert in to csv excel format

Apr 27 2022 2:47 PM

Hi, I  am implimenting some functionality but I am stuck on some logic..All documentation related to multiple text file merge is related to save that to folder.but i dont want to save that after merge.i need to convert  to csv and merge.like below code merge and save into disk.

using (var output = new StreamWriter("D:\\TMP\\output"))
{
foreach (var file in Directory.GetFiles("D:\\TMP", "*.*")){
using (var input = new StreamReader(file))
{
output.WriteLine(input.ReadToEnd());}}
}

here are my requirements..

1.want to search some directory and  get specific named .txt files(getting files by partial names)

2.I want to merge these multiple text files in to one text file

(remove repeating heading from each txt file ie: only one heading is needed.In all txt files headings are same but i need to avoid duplicate heading)

3.this merged txt file i want to convert in to .csv file and save in to my destination path.This csv file would be the end result

What I have tried:

string folderPath = @"C:/Temp/";
string destfile=@"C:/CSVFOLDER/sample.csv";
StreamWriter csvfile;
string[] lines, cells;
DirectoryInfo dir= new DirectoryInfo(folderPath);
FileInfo[] files = dir.GetFiles("unit*", SearchOption.TopDirectoryOnly); //txt file starting with unit i have to take from folder

foreach (var item in files)
{
    lines = File.ReadAllLines(file); //how to fix string issue here?-i cant do this with file type
    csvfile = new StreamWriter(destfile);
    for (int x = 0; x < lines.Length; x++)
    {
        cells = lines[x].Split(new Char[] { '\t', ';' });
        for (int j = 0; j < cells.Length; j++)
            csvfile.Write(cells[j] + "\t");
        csvfile.WriteLine();
    }
    csvfile.Close();
}

Cannot happening merge & convert also.Please help


Answers (12)