假设我想在其内部移动一个文件夹,其以前的内容为空,但对于新文件夹,我将如何最好地使用代码来处理它。通常,在资源管理器中,您可以通过剪切文件夹的内容并将其放置在原始文件夹内创建的新文件夹中来执行此操作。
IE
原始路径:C:\Users\Previous
新路径:C:\Users\Previous\Previous
由于您想将文件夹及其内容移动到具有相同名称的子文件夹中,您可以执行以下操作:
private void button1_Click(object sender, EventArgs e)
{
CopyContentsToSubFolderWithSameName(@"C:\Users\Previous");
}
private void CopyContentsToSubFolderWithSameName(string path)
{
DirectoryInfo currDir = new DirectoryInfo(path);
DirectoryInfo subDir =
Directory.CreateDirectory(Path.Combine(currDir.FullName, currDir.Name));
IEnumerable<DirectoryInfo> parentFolders =
subDir.Parent.EnumerateDirectories();
// Copy files in the current directory to the destination directory
foreach (FileInfo file in currDir.GetFiles())
{
file.MoveTo(Path.Combine(subDir.FullName, file.Name));
}
// Copy directories (including files) in the current directory
// to the destination directory
foreach (DirectoryInfo dir in parentFolders)
{
if (dir.Name != subDir.Name)
{
dir.MoveTo(Path.Combine(subDir.FullName, dir.Name));
}
}
}