C#将一个目录与另一个目录合并 [英] C# merge one directory with another

查看:146
本文介绍了C#将一个目录与另一个目录合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自动更新C#程序。它将下载一个rar文件,将更新的新文件保存到某些软件中。 rar文件的结构就像软件的基本目录,但只包含已更改或新的文件/文件夹。有没有一个简单的方法来合并这些文件/文件夹到目的地目录,所以如果文件/文件夹已经存在,它将被替换,如果不是,它将被添加,或者我必须手动走过每个文件/文件夹,自己做这个?只希望有一个很好的小合并功能,.NET有:)

解决方案

DirectoryInfo类


以下示例演示如何复制目录及其内容。

  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 :)

解决方案

DirectoryInfo Class

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆