简体   繁体   中英

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 '.

I'd it recursively - maybe something like the below sudo 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);
    }
}

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