Sample code
string directory =@"D:\";
string[] fiels = System.IO.Directory.GetFiles(directory);
var fileGroups =fiels.Select(f=>System.IO.Path.GetFileName(f))
.Where(f=>f.Split('_').Length==3)
.GroupBy(f=> f.Substring(0,f.LastIndexOf('_'))).ToList();
foreach(var g in fileGroups)
{
string newFileName = g.Key+".txt";
string newfileContent ="";
foreach( var f in g)
{
newfileContent +=
System.IO.File.ReadAllText(System.IO.Path.Combine(directory, f));
}
System.IO.File.WriteAllText(System.IO.Path.Combine(directory, newFileName),
newfileContent);
}
I have used several LINQ and System.IO methods, if you you not understand anything please ask.
1. I'm taking all the files in the directory using
Directory.GetFiles
method
2. then filder and get only the files with the format
xxxx_xxxx_xx
Using LiNQ and then group the result based on the file name without final number.
3. loop the result and create new file with the content of grouped files.