namespace Demo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public string source; public string target; public int count=1; private void btn_StartCopy_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtSource.Text)||string.IsNullOrEmpty(txtTarget.Text)) { MessageBox.Show("路径不能为空!"); } else { source = txtSource.Text;//原路径 target = txtTarget.Text;//目标路径 try { ListFiles(new DirectoryInfo(source)); MessageBox.Show("复制完成"+count+"文件"); } catch (IOException ex) { Console.WriteLine(ex.Message); } } } /// <summary> /// //递归遍历所有文件包括子文件夹下的文件 并对word excel pdf文件进行复制到目标路径 /// </summary> /// <param name="info"></param> public void ListFiles(FileSystemInfo info) { if (!info.Exists) { return; } DirectoryInfo dir = info as DirectoryInfo; //不是目录 if (dir == null) { return; } FileSystemInfo[] files = dir.GetFileSystemInfos(); for (int i = 0; i < files.Length; i++) { FileInfo file = files[i] as FileInfo; //是文件 if (file != null) { string[] arr = file.Name.Split(new char[] { '.' }); arr[arr.Length - 1] = arr[arr.Length - 1].ToLower(); if (arr[arr.Length - 1] == "doc" || arr[arr.Length - 1] == "docx") { //复制文件 (为true是覆盖同名文件) File.Copy(file.DirectoryName + @"\" + file.Name, Path.Combine(target, file.Name), true); count++; } if (arr[arr.Length - 1] == "xls" || arr[arr.Length - 1] == "xlsx") { //复制文件 (为true是覆盖同名文件) File.Copy(file.DirectoryName + @"\" + file.Name, Path.Combine(target, file.Name), true); count++; } if (arr[arr.Length - 1] == "pdf") { //复制文件 (为true是覆盖同名文件) File.Copy(file.DirectoryName + @"\" + file.Name, Path.Combine(target, file.Name), true); count++; } } //对于子目录,进行递归调用 else { ListFiles(files[i]); } } } } }