我在C#中找到了一个用于执行递归文件复制的小片段,但我有点难过.我基本上需要将目录结构复制到另一个位置,沿着这条线......
来源:C:\ data\servers\mc
目标:E:\ mc
我现在的复制功能代码是......
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(baseDir, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(baseDir, targetDir));
}
// Copy each file into it’s new directory.
foreach (string file in Directory.GetFiles(baseDir, "*.*", SearchOption.AllDirectories))
{
Console.WriteLine(@"Copying {0}\{1}", targetDir, Path.GetFileName(file));
if (!CopyFile(file, Path.Combine(targetDir, Path.GetFileName(file)), false))
{
int err = Marshal.GetLastWin32Error();
Console.WriteLine("[ERROR] CopyFile Failed on {0} with code {1}", file, err);
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,在第二个范围内,我要么:
Path.GetFileName(file)以获得实际文件名不带路径,但我失去了目录"MC"的目录结构或无论哪种方式,我都要做一些讨厌的字符串工作.有没有一种很好的方法在C#中执行此操作(我对.NET API缺乏了解导致我过度复杂化的事情)
M4N*_*M4N 24
MSDN有一个完整的示例:如何:复制目录
using System;
using System.IO;
class DirectoryCopyExample
{
static void Main()
{
// Copy from the current directory, include subdirectories.
DirectoryCopy(".", @".\temp", true);
}
private static void DirectoryCopy(string sourceDirName, string destDirName,
bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
bpg*_*rgo -2
代替
foreach (string file in Directory.GetFiles(baseDir, "*.*", SearchOption.AllDirectories))
{
Run Code Online (Sandbox Code Playgroud)
做这样的事情
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17173 次 |
| 最近记录: |