我一直在使用以下几行来搜索特定文件类型的文件夹结构,然后复制这些文件类型并保持其原始文件夹结构。它工作得很好。我可以对我的方法进行任何修改以仅复制包含过滤文件类型的目录吗?
*edit:我可以让用户使用名为 txtFilter 的文本框,只选择一组文件(例如 *.dwg 或 *.pdf)。
private void button1_Click(object sender, EventArgs e)
{
string sourceFolder = txtSource.Text;
string destinationFolder = txtDestination.Text;
CopyFolderContents(sourceFolder, destinationFolder);
}
// Copies the contents of a folder, including subfolders to an other folder, overwriting existing files
public void CopyFolderContents(string sourceFolder, string destinationFolder)
{
string filter = txtFilter.Text;
if (Directory.Exists(sourceFolder))
{
// Copy folder structure
foreach (string sourceSubFolder in Directory.GetDirectories(sourceFolder, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(sourceSubFolder.Replace(sourceFolder, destinationFolder));
}
// Copy files
foreach (string sourceFile in Directory.GetFiles(sourceFolder, filter, SearchOption.AllDirectories))
{
string destinationFile = sourceFile.Replace(sourceFolder, destinationFolder);
File.Copy(sourceFile, destinationFile, true);
}
}
}