David
David

Reputation: 33

Only acting on files which have the same filename structure in C#

I have a directory which I am watching for files to be added. when files are added my program kick in and does stuff with the contents of the file. However, I have different files with different filename structures. The aim of the program is to deal with all the files that have the same structure first, then move on to the next etc. Heres an example:

BT424HH-4294967298-4294967301-201807021436.xml
BT424HH-4294967298-4294954545-201807034543.xml
BT424HH-4294967298-4294934543-201807028768.xml
BT424HH-4294955655-4294921321-201807065465.xml
BT424HH-4294955655-4294932422-201807023243.xml

In this case I have three files with the same starting structure:

BT424HH-4294967298

I would like to create a new XML file, parse the contents of the three files into one file, once thats completed, move on to the rest of the files in the directory and do the same (create a new file and parse the xml from the files into a new file)

 string[] files = Dir.Split('-');
 string FilePostcode = files[0];
 string FileIdentifier = files[1];
 string currentLocation = FilePostcode + FileIdentifier;

However Im not too sure how to deal with the loop for the files, as in this case I only want the first three with the same name before I deal with the next two with the same name.

I hope this makes sense...

Thanks in advance

Upvotes: 3

Views: 64

Answers (2)

nvoigt
nvoigt

Reputation: 77294

You can just Group your files By the key you want:

public static string GetGroupIdentifier(string path)
{
   var file = System.IO.Path.GetFileNameWithoutExtension(path);

   // take only the first two parts
   var id = string.Join("-", file.Split('-').Take(2));

   return id;
}

public static void GroupFilesInFolder(string path)
{
    foreach(var fileGroup in Directory.GetFiles(path, "*.xml").GroupBy(GetGroupIdentifier))
    {
        Console.WriteLine("For identifier " + fileGroup.Key);
        foreach(var file in fileGroup)
        {
            Console.WriteLine(" - " + file);
        }

        // insert logic to merge the files for this key and do something with the result
    }
}

Upvotes: 2

Mel Gerats
Mel Gerats

Reputation: 2252

Directory.GetFiles(string, string) allows you to search a directory for all files matching a pattern. https://msdn.microsoft.com/en-us/library/wz42302f(v=vs.110).aspx

If you have a list of all the starting structures in patterns:

foreach(var pattern in patterns)
{
    foreach(var file in Directory.GetFiles(path, pattern))
    {
        //Merge files
    }
}

Upvotes: 2

Related Questions