首页 > 解决方案 > 将具有相同文件名的所有文件移动到C#中的文件夹

问题描述

我有一个包含一堆文件的文件夹,例如:

example1.mp4
example1-logo.png
example1-footer.png
example2.mp4
example2-logo.png
example2-footer.png

该程序应创建 2 个文件夹,其中包含文件。

示例 1 文件夹:

example1.mp4
example1-logo.png
example1-footer.png

示例 2 文件夹:

example2.mp4
example2-logo.png
example2-footer.png

这是我到目前为止所做的:

using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.WindowsAPICodePack.Dialogs;

CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.Multiselect = true;
dialog.IsFolderPicker = true;

if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
    foreach (string folder in dialog.FileNames)
    {
        foreach (string file in Directory.EnumerateFiles(folder))
        {
            // Do something with the files
        }
                    
    }
                
}
else
    MessageBox.Show("You must select a folder!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

不太确定从这里去哪里,有什么建议吗?

标签: c#filedirectory

解决方案


您可以通过破折号分隔符拆分文件名(不带扩展名)以获取字符串数组并按第一个元素分组,该元素在您的示例example1中用于第一组和example2第二组。然后循环以创建目标目录,并循环每个以复制/移动文件。

这是一个例子:

using System.IO;
using System.Linq;

//The caller..
var srcFolder = @"..."; //The source folder.
var desFolder = @"..."; //The destination folder.
var groups = Directory.EnumerateFiles(srcFolder)
    .Select(x => new FileInfo(x))
    .GroupBy(x => Path.GetFileNameWithoutExtension(x.Name).Split('-').First());

foreach (var group in groups)
{
    var groupFolder = Path.Combine(desFolder, group.Key);

    Directory.CreateDirectory(groupFolder);

    foreach (var file in group)
        // Or file.MoveTo(...)
        file.CopyTo(Path.Combine(groupFolder, file.Name), true);
}

推荐阅读