我有多个文件夹。它们以文件扩展名命名。 (例如:-doc,dwg,jpg ....等),我的列表框数据源包含更多文件。(例如:-abc.dwg,beauty.jpg,arc.doc .....)我想移动文档文件到doc文件夹,jpg文件到jpg文件夹,dwg文件到dwg文件夹...等 怎么做单按钮单击>>“创建文件夹”按钮使用
List<string> fileNames = null;
List<string> fileExtensions = null;
private void btn_list_Click(object sender, EventArgs e)
{
listBox_ex.Items.Clear();
using (FolderBrowserDialog FBD = new FolderBrowserDialog())
{
if (FBD.ShowDialog() == DialogResult.OK)
{
lbl_path.Text = FBD.SelectedPath;
fileNames = Directory.GetFiles(FBD.SelectedPath).ToList();
fileExtensions = fileNames.Select(item => Path.GetExtension(item)
.Replace(".", "")).Distinct().OrderBy(n => n).ToList();
listBox_name.DataSource = fileNames.Select(f => Path.GetFileName(f)).ToList();
listBox_ex.DataSource = fileExtensions;
}
}
}
private void btn_CreateFolder_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog FBD = new FolderBrowserDialog())
{
if (FBD.ShowDialog() == DialogResult.OK)
{
lbl_pathCreated.Text = FBD.SelectedPath;
fileExtensions.ForEach(item =>
Directory.CreateDirectory(Path.Combine(FBD.SelectedPath, item)));
}
}
}
答案 0 :(得分:2)
简短的答案是,您只需调用File.Move
,并将完整路径作为第一个参数传递给现有文件,并传递目标的完整路径和文件名。
您可以构建目标路径,然后移动文件,例如:
foreach (string file in fileNames)
{
// Build the destination path
var destination = Path.Combine(
FBD.SelectedPath, // The root destination folder
Path.GetExtension(file).Replace(".", ""), // The file extension folder
Path.GetFileName(file)); // The file name (including extension)
// Move the file
File.Move(file, destination);
}