📅  最后修改于: 2023-12-03 14:39:45.859000             🧑  作者: Mango
在C#中复制目录并不是一项非常直接的任务,但仍然是一个容易实现的任务。本文将介绍如何使用C#代码来复制整个目录。
private static void CopyDirectory(string sourceDir, string targetDir)
{
// code goes here
}
if (!Directory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir);
}
string[] files = Directory.GetFiles(sourceDir);
foreach (string file in files)
{
// code goes here
}
string fileName = Path.GetFileName(file);
string destFile = Path.Combine(targetDir, fileName);
File.Copy(file, destFile, true);
string[] directories = Directory.GetDirectories(sourceDir);
foreach (string directory in directories)
{
// code goes here
}
string dirName = Path.GetFileName(directory);
string destDir = Path.Combine(targetDir, dirName);
CopyDirectory(directory, destDir);
string sourceDir = @"C:\Users\JohnDoe\Documents\Source";
string targetDir = @"C:\Users\JohnDoe\Documents\Target";
CopyDirectory(sourceDir, targetDir);
using System.IO;
namespace CopyDirectoryExample
{
class Program
{
static void Main(string[] args)
{
string sourceDir = @"C:\Users\JohnDoe\Documents\Source";
string targetDir = @"C:\Users\JohnDoe\Documents\Target";
CopyDirectory(sourceDir, targetDir);
}
private static void CopyDirectory(string sourceDir, string targetDir)
{
if (!Directory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir);
}
string[] files = Directory.GetFiles(sourceDir);
foreach (string file in files)
{
string fileName = Path.GetFileName(file);
string destFile = Path.Combine(targetDir, fileName);
File.Copy(file, destFile, true);
}
string[] directories = Directory.GetDirectories(sourceDir);
foreach (string directory in directories)
{
string dirName = Path.GetFileName(directory);
string destDir = Path.Combine(targetDir, dirName);
CopyDirectory(directory, destDir);
}
}
}
}
以上就是如何在C#中复制目录的完整教程。