簡體   English   中英

從目錄復制所有文件而不創建子目錄

[英]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。

錯誤的一個例子:

找不到路徑'C:\\ Users \\ username \\ AppData \\ Local \\ Temp \\ C#Temporary Files \\ external directory \\ sub-directory \\ filename '的一部分。

我遞歸地 - 可能是類似下面的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