如何将文件移动到多个文件夹?

我有多个文件夹。它们以文件扩展名命名。(例如:- 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)));

        }

    }

}


守着一只汪
浏览 143回答 1
1回答

胡说叔叔

简短的回答是您只需调用File.Move, 并将现有文件的完整路径作为第一个参数传递,并传递目标的完整路径和文件名。您可以构建目标路径,然后像这样移动文件:foreach (string file in fileNames){&nbsp; &nbsp; // Build the destination path&nbsp; &nbsp; var destination = Path.Combine(&nbsp; &nbsp; &nbsp; &nbsp; FBD.SelectedPath,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// The root destination folder&nbsp; &nbsp; &nbsp; &nbsp; Path.GetExtension(file).Replace(".", ""),&nbsp; &nbsp;// The file extension folder&nbsp; &nbsp; &nbsp; &nbsp; Path.GetFileName(file));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // The file name (including extension)&nbsp; &nbsp; // Move the file&nbsp; &nbsp; File.Move(file, destination);}
打开App,查看更多内容
随时随地看视频慕课网APP