简体   繁体   中英

How to copy files in subdirectory?

How to modify the code to copy and files in subdirectoryes of tempDownloadFolder?

private void moveFiles()
{
   DirectoryInfo di = new DirectoryInfo(tempDownloadFolder);
   FileInfo[] files = di.GetFiles();

   foreach (FileInfo fi in files)
   {
       if (fi.Name != downloadFile)
        File.Copy(tempDownloadFolder + fi.Name, destinationFolder + fi.Name, true);
   }

}

You need to do a recursive search.

very rough example:

    private void copyFiles(string filePath)
    {
        DirectoryInfo di = new DirectoryInfo(filePath);
        FileInfo[] files = di.GetFiles();

        foreach (FileInfo fi in files)
        {
            // test if fi is a directory
            // if so call copyFiles(fi.FullName) again
            // else execute the following
            if (fi.Name != downloadFile) File.Copy(filePath+ fi.Name, destinationFolder + fi.Name, true);
        }

    }

If you want files of all subdirectories use the SearchOption parameter:

DirectoryInfo di = new DirectoryInfo(tempDownloadFolder);
di.GetFiles("*.*", SearchOption.AllDirectories);

FileInfo[] files = di.GetFiles();

foreach (FileInfo fi in files)
{
   if (fi.Name != downloadFile)
   File.Copy(tempDownloadFolder + fi.Name, destinationFolder + fi.Name, true);
}

将File.Copy行替换为

File.Copy(fi.FullName, Path.Combine(destinationFolder, fi.Name), true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM