C# 仅作用于在C中具有相同文件名结构的文件#

C# 仅作用于在C中具有相同文件名结构的文件#,c#,C#,我有一个目录,我正在监视要添加的文件。当文件被添加时,我的程序启动并处理文件的内容。 但是,我有不同的文件名结构。该程序的目的是首先处理具有相同结构的所有文件,然后继续处理下一个文件等。下面是一个示例: BT424HH-4294967298-4294967301-201807021436.xml BT424HH-4294967298-4294954545-201807034543.xml BT424HH-4294967298-4294934543-201807028768.xml BT424HH

我有一个目录,我正在监视要添加的文件。当文件被添加时,我的程序启动并处理文件的内容。 但是,我有不同的文件名结构。该程序的目的是首先处理具有相同结构的所有文件,然后继续处理下一个文件等。下面是一个示例:

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
在本例中,我有三个具有相同起始结构的文件:

BT424HH-4294967298
我想创建一个新的XML文件,将三个文件的内容解析为一个文件,完成后,转到目录中的其余文件并执行相同的操作(创建一个新文件并将文件中的XML解析为一个新文件)

但是,我不太确定如何处理文件的循环,因为在本例中,我只希望前三个文件具有相同的名称,然后再处理下两个文件具有相同的名称

我希望这是有意义的

提前感谢目录。GetFiles(string,string)允许您在目录中搜索与模式匹配的所有文件。

如果您有
模式中所有起始结构的列表

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

您只需按所需的键对文件进行分组即可:

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
    }
}

多亏了这一点,我怎么知道它是组中的最后一个文件呢?你可以用一个简单的
for
循环替换
foreach
,但是可能有更好的方法来实现你想要的。为什么您需要知道某个文件是否是组中的最后一个文件?这样我就可以将结束xml附加到该文件中,关闭它,然后转到下一组文件并从中创建新的xml文件。:-)当foreach在文件上的循环完成时就关闭它?
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
    }
}