c# - 将具有相同文件名的所有文件移动到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);
不太确定从这里去哪里,有什么建议吗?
解决方案
您可以通过破折号分隔符拆分文件名(不带扩展名)以获取字符串数组并按第一个元素分组,该元素在您的示例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);
}
推荐阅读
- json - 在使用 React Native 的某些记录后无法将值保存到 localMongoDB
- android - 如何将 android 模块用作应用程序和库
- java - How to extract the dynamic values of the id attributes of the table elements using Selenium and Java
- shopify - 关于“主题获取”命令 shopify 的问题
- gradle - 如何从 Gradle Kotlin DSL 表达式中访问项目版本?
- angular - 路由到具有不同参数的相同网址后,页面上的数据未更新
- reactjs - 如何修复反应表中的分页重置问题?
- sql - 通过调用存储过程更新表的 Null 记录会引发错误“子查询返回多个值”
- php - 如何解决这个问题“未定义的变量:类别”?
- clickatell - Clickatell 从沙盒帐户向 iphone 发送空白消息