复制目录中的所有文件而不创建子目录

Copy all files from a directory without creating subdirectories

我正在尝试获取一个目录并在 TEMP 中创建一个新目录,其中包含原始目录中的所有文件,但不创建其他子目录。

这是我目前的情况:

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

这适用于复制目录本身中的文件,但不适用于子目录中的文件。相反,它会抛出错误:

System.IO.DirectoryNotFoundException.

错误示例:

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

我递归地进行了 - 可能类似于下面的伪代码...未测试..

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