简体   繁体   English

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

[英]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. 我试图获取一个目录并在TEMP中创建一个新目录,其中包含原始目录中的所有文件,但不创建其他子目录。

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. 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 '. 找不到路径'C:\\ Users \\ username \\ AppData \\ Local \\ Temp \\ C#Temporary Files \\ external directory \\ sub-directory \\ filename '的一部分。

I'd it recursively - maybe something like the below sudo code... not tested.. 我递归地 - 可能是类似下面的sudo代码...没有经过测试..

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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