2

假设我想在其内部移动一个文件夹,其以前的内容为空,但对于新文件夹,我将如何最好地使用代码来处理它。通常,在资源管理器中,您可以通过剪切文件夹的内容并将其放置在原始文件夹内创建的新文件夹中来执行此操作。

IE

原始路径:C:\Users\Previous

新路径:C:\Users\Previous\Previous

4

2 回答 2

0

由于您想将文件夹及其内容移动到具有相同名称的子文件夹中,您可以执行以下操作:

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));
        }
    }
}
于 2013-08-08T13:57:03.843 回答
0
  1. 创建临时文件夹:c:\user\temp
  2. 使用Move from c:\user\previous移动目录到:c:\user\temp
  3. 将临时文件夹重命名为Move from c:\user\temp to c:\user\previous
于 2013-08-08T12:48:03.430 回答