2

我可以简单地使用文件来做到这一点,如下所示:

public static void MoveAllFilesFromDesktopToJDrive()
        {
            DirectoryInfo di = new DirectoryInfo(@"C:\Users\Tafe\Desktop\");
            DirectoryInfo Jdrive = new DirectoryInfo(@"J:\");

            foreach (FileInfo fi in di.GetFiles())
            {
                if (Path.GetFileName(fi.FullName) != "desktop.ini")
                {                      
                    fi.MoveTo(Jdrive.FullName + Path.GetFileName(fi.FullName));
                }    
            }
        }

但是在目录上尝试相同的操作告诉我我不能跨卷移动目录。好的,所以这就是我尝试过的:

 public static void MoveAllDirsFromDeskTopToJDrive()
        {
            DirectoryInfo di = new DirectoryInfo(@"C:\Users\Tafe\Desktop\");
            DirectoryInfo Jdrive = new DirectoryInfo(@"J:\");

            foreach (DirectoryInfo dirs in di.GetDirectories())
            {
               Directory.CreateDirectory(Jdrive + Path.GetFileName(dirs.FullName)); 

            }
        }

这会复制文件的名称,但不会复制内容,我会像使用我的MoveAllFilesFromDesktopToJDrive()方法一样移动内容,但是目录包含子目录和子目录等,所以我无法弄清楚。我对递归有一点了解,但还不足以尝试这个。还有,不会那么难吧?API中必须有更好的东西来促进这一点?如果没有,完成此方法的任何帮助MoveAllFilesFromDesktopToJDrive()都将成为救命稻草!

4

1 回答 1

0

尝试在代码中的某处循环:

    string fileName = "test.txt";
    string sourcePath = @"C:\Users\Public\TestFolder";
    string targetPath =  @"C:\Users\Public\TestFolder\SubDir";

    // Use Path class to manipulate file and directory paths. 
    string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
    string destFile = System.IO.Path.Combine(targetPath, fileName);

    // To copy a folder's contents to a new location: 
    // Create a new target folder, if necessary. 
    if (!System.IO.Directory.Exists(targetPath))
    {
        System.IO.Directory.CreateDirectory(targetPath);
    }

    System.IO.File.Copy(sourceFile, destFile, true);

有关详细信息,请访问此链接:http: //msdn.microsoft.com/en-us/library/cc148994.aspx

于 2012-11-05T04:32:38.153 回答