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

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

问题描述

我有一个autoupdater C#程序。它会下载保存更改或新的文件更新一些软件RAR文件。 RAR文件有它的结构就像软件的基本目录,但只包含更改或新的文件/文件夹。有没有一种简单的方法将这些文件/文件夹合并到目标目录因此,如果文件/文件夹已经存在,它会被取代,如果没有它会被添加或者我必须通过每一个文件手动行走/文件夹,这样做我自己?只是希望有是.NET有一个可爱的小合并功能:)


解决方案

DirectoryInfo类




下面的例子演示了如何复制目录及其内容。

 公共静态无效CopyAll(DirectoryInfo的来源, DirectoryInfo的目标)
{
如果(source.FullName.ToLower()== target.FullName.ToLower())
{
的回报;
}

//检查目标目录是否存在,如果没有,创建它。
如果(Directory.Exists(target.FullName)==假)
{
Directory.CreateDirectory(target.FullName);
}

//复制每个文件到它的新目录中。
的foreach(FileInfo的网络连接source.GetFiles())
{
Console.WriteLine(@复制{0} \ {1},target.FullName,fi.Name);
fi.CopyTo(Path.Combine(target.ToString(),fi.Name),TRUE);
}

//复制每个子目录使用递归。
的foreach(DirectoryInfo的diSourceSubDir在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天全站免登陆