Search code examples
c#folderbrowserdialog

Copy all files from a directory without creating subdirectories


I am trying to take a directory and create a new directory in TEMP, that contains all the files in the original directory, but not create additional sub-directories.

Here is what I have so far:

Directory.CreateDirectory(Path.Combine(Path.GetTempPath() + "C# Temporary Files"));
            string lastFolder = new DirectoryInfo(folders.SelectedPath).Name;

foreach (string newPath in Directory.GetFiles(folders.SelectedPath, "*.*",SearchOption.AllDirectories)
                    .Where(s=>s.EndsWith(".c")|| s.EndsWith(".h")))
                {
                    File.Copy(newPath, newPath.Replace(folders.SelectedPath, Path.GetTempPath() + "C# Temporary Files\\" + GlobalVar.GlobalInt));
                }

This works in copying files that are in the directory itself, but not files in subdirectories. Instead it throws the error:

System.IO.DirectoryNotFoundException.

An example of the error:

Could not find a part of the path 'C:\Users\username\AppData\Local\Temp\C# Temporary Files\outer directory\sub-directory\filename'.


Solution

  • I'd it recursively - maybe something like the below pseudo code... not tested..

    public void CopyRecursive(string path, string newLocation)
    {
        foreach(var file in DirectoryInfo.GetFiles(path))
        {
            File.Copy(file.FullName, newLocation + file.Name);
        }
    
        foreach(var dir in DirectoryInfo.GetDirectories(path))
        {
            CopyRecursive(path + dir.Name, newLocation);
        }
    }