Kras Kj
Kras Kj

Reputation: 1

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);
   }

}

Upvotes: 0

Views: 274

Answers (4)

JeffRSon
JeffRSon

Reputation: 11186

Replace the File.Copy line by

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

Upvotes: 0

DaveDev
DaveDev

Reputation: 42185

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);
        }

    }

Upvotes: 2

Carlos Landeras
Carlos Landeras

Reputation: 11063

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);
}

Upvotes: 1

Related Questions