using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FilesCopy
{
public class FileCopier
{
private string source;
private string target;
private string fileType;
public void FileCopier(string source,string target,string fileType="")
{
this.source = source;
this.target = target;
this.fileType = fileType;
}
public void Copy(string source, string target, string fileType = "")
{
if (!Directory.Exists(source))
{
MessageBox.Show("源文件夹不存在");
return;
}
if (!Directory.Exists(target))
{
MessageBox.Show("目标文件夹不存在");
return;
}
List<FileItem> lst = new List<FileItem>();
lock (lst)
{
GetFile(lst, new DirectoryInfo(source),target,fileType);
}
foreach (var f in lst)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(CopyFile), f);
}
}
void CopyFile(object model)
{
var item = model as FileItem;
string targetFile = Path.Combine(item.Target, item.Name + "." + item.FileType);
File.Copy(item.Path, targetFile);
}
void GetFile(List<FileItem> lst, DirectoryInfo sorce,string target,string fileType)
{
DirectoryInfo[] lstD = sorce.GetDirectories();
if (lstD != null && lstD.Count() != 0)
{
foreach (var d in lstD)
{
GetFile(lst, d,target,fileType);
}
}
FileInfo[] lstF = sorce.GetFiles();
if (lstF != null && lstF.Count() != 0)
{
for (int i = 0; i < lstF.Count(); i++)
{
if (!string.IsNullOrEmpty(fileType))
{
if (lstF[i].Extension != fileType)
{
continue;
}
}
lst.Add(new FileItem()
{
Name = sorce.Name + i.ToString(),
Path = lstF[i].FullName,
FileType = lstF[i].Extension
});
}
}
}
class FileItem
{
public string Target { get; set; }
public string Path { get; set; }
public string FileType { get; set; }
public string Name { get; set; }
}
}
}