Click here to Skip to main content
15,888,221 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have a csv file in the following format.
col1  col2
a      aa
b      ba
CSV    file 2
col1   col2
c      a
d      b

Final OutPut:
col1  col2
a     aa
b     ba
c     a
d     b

My code is:
C#
var fiels = new DirectoryInfo(Source).GetFiles("*_*.csv")

             .OrderBy(f => f.CreationTime);


             var fileGroups = (from file in fiels group file.Name by file.Name.Substring(0, file.Name.IndexOf('_', 1)));


             foreach (var g in fileGroups)
             {
                 string newFileName = g.Key + ".csv";
                 string newfileContent = "";
                 foreach (var f in g)
                 {
                     newfileContent +=
                             System.IO.File.ReadAllText(System.IO.Path.Combine(Source, f));

                     count++;
                 }

                 System.IO.File.WriteAllText(System.IO.Path.Combine(To_be_processed, newFileName),
                                                newfileContent);

             }


My output is
col1  col2
a      aa
b      ba
col1  col2
c      a
d      b

How can i get common hearder while merging?
Posted
Updated 26-May-14 23:54pm
v2
Comments
Richard MacCutchan 27-May-14 4:01am    
You should use ReadAllText for the first file, but for the second and subsequent files you need to read line by line and drop the header line.
vinodhini sekar 27-May-14 5:20am    
Thanks.

1 solution

C#
if (newfileContent == "")
                        {
                            newfileContent +=
                                    System.IO.File.ReadAllText(System.IO.Path.Combine(Source, f));
                        }
                        else
                        {
                            using (StreamReader Read = new StreamReader(Source + "\\" + f))
                            {
                                string Header = Read.ReadLine();
                                while ((line = Read.ReadLine()) != null)
                                {
                                    newfileContent += line;
                                    newfileContent += Environment.NewLine;

                                }
                            }
                        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900