直接上效果图和代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProcessItems
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// 启用拖放
treeViewItems.AllowDrop = true;
// 拖放进入事件
treeViewItems.DragEnter += new DragEventHandler(treeView_DragEnter);
// 拖放事件
treeViewItems.DragDrop += new DragEventHandler(treeView_DragDrop);
// 设置窗体启动时居中显示
this.StartPosition = FormStartPosition.CenterScreen;
}
// 允许拖放的文件类型
private void treeView_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy; // 或者其他效果
}
else
{
e.Effect = DragDropEffects.None;
}
}
// 处理拖放事件
private void treeView_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
// 检查文件是否存在
if (/*File.Exists(file) || */Directory.Exists(file))
{
// 在这里添加文件到TreeView的逻辑
treeViewItems.Nodes.Add(new TreeNode(file));
}
}
}
private void buttonOK_Click(object sender, EventArgs e)
{
foreach (var dir in treeViewItems.Nodes)
{
TreeNode node = dir as TreeNode;
string stCurDir = node.Text;
MoveFilesToSplitDirectories(stCurDir, Convert.ToInt32(numCountLimit.Value), false);
}
MessageBox.Show("处理完成!", "提示!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
static bool MoveFilesToSplitDirectories(string directoryPath, int filesPerDirectory, bool includeSubdirectories)
{
if (!Directory.Exists(directoryPath))
{
Console.WriteLine("The specified directory does not exist.");
return false;
}
var files = new List<string>();
// Get files from the directory and optionally its subdirectories
if (includeSubdirectories)
{
files.AddRange(Directory.GetFiles(directoryPath, "*", SearchOption.AllDirectories));
}
else
{
files.AddRange(Directory.GetFiles(directoryPath));
}
if (files.Count == 0)
{
Console.WriteLine("No files found in the directory.");
return false;
}
string directoryName = new DirectoryInfo(directoryPath).Name;
string parentDirectoryPath = Directory.GetParent(directoryPath).FullName;
int directoryCounter = 1;
int fileCounter = 0;
string currentDestDir = Path.Combine(parentDirectoryPath, $"{directoryName}{directoryCounter}");
Directory.CreateDirectory(currentDestDir);
foreach (var file in files)
{
if (fileCounter >= filesPerDirectory)
{
directoryCounter++;
fileCounter = 0;
currentDestDir = Path.Combine(parentDirectoryPath, $"{directoryName}{directoryCounter}");
Directory.CreateDirectory(currentDestDir);
}
string destFile = Path.Combine(currentDestDir, Path.GetFileName(file));
File.Move(file, destFile);
fileCounter++;
}
return true;
}
}
}