簡體   English   中英

復制目錄下的所有文件

[英]Copy all files in directory

如何將一個目錄中的所有內容復制到另一個目錄而不循環遍歷每個文件?

你不能。 DirectoryDirectoryInfo都不提供Copy方法。 您需要自己實現這一點。

void Copy(string sourceDir, string targetDir)
{
    Directory.CreateDirectory(targetDir);

    foreach(var file in Directory.GetFiles(sourceDir))
        File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));

    foreach(var directory in Directory.GetDirectories(sourceDir))
        Copy(directory, Path.Combine(targetDir, Path.GetFileName(directory)));
}

請閱讀評論以了解這種簡單方法的一些問題。

Msdn 有這方面的指導 -如何:復制目錄

您可以使用 VB 的 FileSystem.CopyDirectory 方法來簡化任務:

using Microsoft.VisualBasic.FileIO;

foo(){
    FileSystem.CopyDirectory(directoryPath, tempPath);
}
using System.IO;

string sourcePath = @"D:\test";
string targetPath = @"D:\test_new";
if (!Directory.Exists(targetPath))
{
   Directory.CreateDirectory(targetPath);
}
foreach (var srcPath in Directory.GetFiles(sourcePath))
{
    //Copy the file from sourcepath and place into mentioned target path, 
    //Overwrite the file if same file is exist in target path
    File.Copy(srcPath, srcPath.Replace(sourcePath, targetPath), true);
}

KISS – Keep It Simple Stupid……對於任何情況都是一個很好的經驗法則,包括編程。

這是復制所有文件、文件夾、子文件夾及其所有文件和文件夾同時保持原始層次結構的最簡單方法。 它還顯示了一個很好的 Microsoft Windows 進度對話框。 只需遵循以下基本說明:

1:在 Visual Studio 中打開一個新的 C# 控制台應用程序——版本(隨便)

2:從菜單欄; 轉到“工具 - Nuget 包管理器 - 管理解決方案的 Nuget 包”在 Nuget 包管理器搜索框中,鍵入 - “Microsoft.VisualBasic”並選擇“.Net”包。

3:回到“Program.cs”頁面,添加以下“using”語句:

使用系統;

使用 Microsoft.VisualBasic.FileIO;

4:在“Main”方法中,鍵入下面提供的代碼,用您的文件夾/驅動器替換源路徑和目標路徑。

5:“Console.WriteLine”行只顯示一條消息,它正在復制和“請待機”。 這行代碼是完全可選的。 這個過程不需要工作。

6:“FileSystem.CopyDirectory”命令是一個基本的復制功能,用於將文件夾和內容復制到新的目的地。 唯一真正的區別是在復制命令的末尾添加了“UIOption.AllDialgs”命令。 這是生成 Microsoft Windows 進度對話框的部分。

現在,將以下代碼添加到您的 C#“Program.cs”頁面。

using System;
using Microsoft.VisualBasic.FileIO;


namespace ProgressDialogBox
{
    class Program
    {
        static void Main(string[] args)
        {

            string sourcePath = @"c:\TestA\TestNew3";
            string destinationPath = @"c:\TestB\TestNew4";

            Console.WriteLine(@"Copying... {0} ... Please stand by ", sourcePath);
            FileSystem.CopyDirectory(sourcePath, destinationPath, UIOption.AllDialogs);

        }
    }
}

整個過程不到 3 分鍾即可創建。 閱讀這篇文章實際上比創建和執行程序需要更長的時間。

享受。

希望這對未來的人有所幫助。

這是我用於參考的 Microsoft 鏈接:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-provide-a-progress-dialog-box-for-file-operations

這很好用! 它將復制子目錄,或者您可以將所有子目錄中的所有文件轉儲到一個位置。

/// AUTHOR : Norm Petroff 
/// <summary>
/// Takes the files from the PathFrom and copies them to the PathTo. 
/// </summary>
/// <param name="pathFrom"></param>
/// <param name="pathTo"></param>
/// <param name="filesOnly">Copies all files from each directory to the "PathTo" and removes directory.</param>
public static void CopyFiles(String pathFrom, String pathTo, Boolean filesOnly)
{
    foreach(String file in Directory.GetFiles(pathFrom))
    {
        // Copy the current file to the new path. 
        File.Copy(file, Path.Combine(pathTo, Path.GetFileName(file)), true);
    }

    // Get all the directories in the current path. 
    foreach (String directory in Directory.GetDirectories(pathFrom))
    { 
         // If files only is true then recursively get all the files. They will be all put in the original "PathTo" location 
         // without the directories they were in. 
         if (filesOnly)
         {
              // Get the files from the current directory in the loop. 
              CopyFiles(directory, pathTo, filesOnly);
         }
         else
         {
              // Create a new path for the current directory in the new location.                      
              var newDirectory = Path.Combine(pathTo, new DirectoryInfo(directory).Name);

              // Copy the directory over to the new path location if it does not already exist. 
              if (!Directory.Exists(newDirectory))
              {
                  Directory.CreateDirectory(newDirectory);
              }
              // Call this routine again with the new path. 
              CopyFiles(directory, newDirectory, filesOnly);
        }
    }
}

你不能。 但是您可以使用某種簡潔的代碼,例如Directory.GetFiles(mydir).ToList().ForEach(f => File.Copy(f, otherdir + "\\\\" + Path.GetFileName(f));

作為外部命令執行xcopy source_directory\\*.* destination_directory 當然,這只適用於 Windows 機器。

雖然 C# 方法效果很好,但它並不總是最佳答案。 通過忽略 C# 方法中的 256 個字符限制,一個簡單的 DOS 批處理腳本可以更好地工作。

robocopy C:\myFiles D:\masterBackup\myFiles /E /V 

我發現 DOS 批處理腳本的唯一缺點是它不會(在某些情況下)使用“robocopy”命令復制 SQL 服務器“mdf”數據文件和“ldf”日志文件。 但這是一個權限問題。

否則,我更多地依賴 DOS 批處理腳本來進行增量備份和完整備份。

Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + @"resources\html")
    .ToList()
    .ForEach(f => File.Copy(f, folder + "\\" + f.Substring(f.LastIndexOf("\\"))));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM