我遇到了真正的问题,直到现在我还是无法解决。我正在使用Visual Studio C#Windows窗体应用程序。 我只想复制名称为20190401、20190402和20190403的“源”文件夹中的“ 2019”文件夹。在“源”文件夹中有随机文件夹,例如“ 2018”,“ 2017”等。我想要的结果是单击按钮后,它将自动仅将“源”文件夹中的“ 2019”文件夹复制到“目标”文件夹,然后仅复制2019文件夹中的3个文本文件。
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
string FROM_DIR = "C:/Users/5004117928/Desktop/Source";
string TO_DIR = "C:/Users/5004117928/Desktop/Target/";
string filename = "t";
public Form1()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
DirectoryInfo diCopyForm = new DirectoryInfo(FROM_DIR);
FileInfo[] fiDiskfiles = diCopyForm.GetFiles();
foreach (FileInfo newfile in fiDiskfiles.Take(3))
{
try
{
if (newfile.Name.StartsWith(filename))
{
File.Copy(newfile.FullName, TO_DIR + newfile.Name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
我希望在单击按钮后输出,所有2019个文件夹都将复制到 “目标”文件夹,其中每个复制的2019文件夹中都有3个文本文件。
答案 0 :(得分:0)
让我们逐步执行例程:
using System.IO;
using System.Linq;
...
// "I just want to copy "2019" folders in " Source"
string FROM_DIR = "C:/Users/5004117928/Desktop/Source";
// "with given name 20190401, 20190402, and 20190403"
HashSet<string> acceptedFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
"20190401", "20190402", "20190403"
};
// "I want is after I click a button then it automatically only "2019" folders"
// Here we enumerate all files to copy:
// - they are from FROM_DIR, 2019 subfolder
// - they are in acceptedFiles ("20190401", "20190402", "20190403")
var files = Directory
.EnumerateFiles(Path.Combine(FROM_DIR, "2019"), "*", SearchOption.TopDirectoryOnly)
.Where(file => acceptedFiles.Contains(Path.GetFileNameWithoutExtension(file)))
.ToArray();
// will copy to "target" folder
string TO_DIR = "C:/Users/5004117928/Desktop/Target";
// Copy:
foreach (var sourceFile in files) {
// for given sourceFile we change its folder
string targetFile = Path.Combine(TO_DIR, Path.GetFileName(sourceFile));
File.Copy(sourceFile, targetFile);
}
编辑:如果您有很多目录可供选择,让我们列举一下tham并添加Where
:
var files = Directory
.EnumerateDirectories(FROM_DIR, "*", SearchOption.TopDirectoryOnly)
.Where(dir => new DirectoryInfo(dir).Name.StartsWith("2019"))
.SelectMany(dir => Directory
.EnumerateFiles(dir, "*")
.Where(file => acceptedFiles.Contains(Path.GetFileNameWithoutExtension(file))))
.ToArray();
...