C#将一个目录与另一个目录合并 [英] C# merge one directory with another
本文介绍了C#将一个目录与另一个目录合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
以下示例演示如何复制目录及其内容。
public static void CopyAll(DirectoryInfo source,DirectoryInfo target)
{
if(source.FullName.ToLower()== target.FullName.ToLower())
{
return;
}
//检查目标目录是否存在,否则创建它。
if(Directory.Exists(target.FullName)== false)
{
Directory.CreateDirectory(target.FullName);
}
//将每个文件复制到其新目录中。
foreach(FileInfo fi in source.GetFiles())
{
Console.WriteLine(@复制{0} \ {1},target.FullName,fi.Name);
fi.CopyTo(Path.Combine(target.ToString(),fi.Name),true);
}
//使用递归复制每个子目录。
foreach(DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir,nextTargetSubDir);
}
}
I have an autoupdater C# program. It will download a rar file that holds the changed or new files for the update to some software. The rar file has it's structure just like the base directory of the software but only contains changed or new files/folders. Is there an easy way to "merge" these files/folders to the destination directory so in that if the file/folder exists already it'll be replaced and if not it'll be added or do I have to manually walk through each file/folder and do this myself? Just hoping there is a nice little merge function that .NET has :)
解决方案
The following example demonstrates how to copy a directory and its contents.
public static void CopyAll(DirectoryInfo source, DirectoryInfo target) { if (source.FullName.ToLower() == target.FullName.ToLower()) { return; } // Check if the target directory exists, if not, create it. if (Directory.Exists(target.FullName) == false) { Directory.CreateDirectory(target.FullName); } // Copy each file into it's new directory. foreach (FileInfo fi in source.GetFiles()) { Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name); fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true); } // Copy each subdirectory using recursion. foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) { DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name); CopyAll(diSourceSubDir, nextTargetSubDir); } }
这篇关于C#将一个目录与另一个目录合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文