在C#中文件夹复制 [英] Folder copy in C#

查看:107
本文介绍了在C#中文件夹复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在C 10的文本文件的文件夹:在我的机器\TEXTFILES\驱动器。我想从我的机器完全复制文件夹TEXTFILES及其内容到另一台机器。如何复制同样使用C#。


解决方案

 使用系统; 
:使用System.IO;

类DirectoryCopyExample
{
静态无效的主要()
{
DirectoryCopy(@,真正的。\temp。);
}

私有静态无效DirectoryCopy(
串sourceDirName,串destDirName,布尔copySubDirs)
{
DirectoryInfo的DIR =新DirectoryInfo的(sourceDirName);
DirectoryInfo的[] =迪尔斯dir.GetDirectories();

//如果源目录不存在,抛出异常。 (!dir.Exists)
如果
{
抛出新DirectoryNotFoundException(
源目录不存在或无法找到:
+ sourceDirName);
}

//如果目标目录不存在,创建它。 (!Directory.Exists(destDirName))
如果
{
Directory.CreateDirectory(destDirName);
}


//获取目录中的文件内容进行复制。
的FileInfo [] =文件dir.GetFiles();

的foreach(在文件的FileInfo文件)
{
//创建文件路径的新副本。
串TEMPPATH = Path.Combine(destDirName,file.Name);

//复制文件。
file.CopyTo(TEMPPATH,FALSE);
}

//如果copySubDirs是真的,复制子目录。
如果(copySubDirs)
{

的foreach(DirectoryInfo的子目录中迪尔斯)
{
//创建子目录。
串TEMPPATH = Path.Combine(destDirName,subdir.Name);

//复制子目录。
DirectoryCopy(subdir.FullName,TEMPPATH,copySubDirs);
}
}
}
}

MSDN


I have a folder with 10 text files at C:\TEXTFILES\ drive in my machine. I want to copy the folder TEXTFILES and its contents completely from my machine to another machine. How to copy the same using C#.

解决方案

using System;
using System.IO;

class DirectoryCopyExample
{
    static void Main()
    {
        DirectoryCopy(".", @".\temp", true);
    }

    private static void DirectoryCopy(
        string sourceDirName, string destDirName, bool copySubDirs)
    {
      DirectoryInfo dir = new DirectoryInfo(sourceDirName);
      DirectoryInfo[] dirs = dir.GetDirectories();

      // If the source directory does not exist, throw an exception.
        if (!dir.Exists)
        {
            throw new DirectoryNotFoundException(
                "Source directory does not exist or could not be found: "
                + sourceDirName);
        }

        // If the destination directory does not exist, create it.
        if (!Directory.Exists(destDirName))
        {
            Directory.CreateDirectory(destDirName);
        }


        // Get the file contents of the directory to copy.
        FileInfo[] files = dir.GetFiles();

        foreach (FileInfo file in files)
        {
            // Create the path to the new copy of the file.
            string temppath = Path.Combine(destDirName, file.Name);

            // Copy the file.
            file.CopyTo(temppath, false);
        }

        // If copySubDirs is true, copy the subdirectories.
        if (copySubDirs)
        {

            foreach (DirectoryInfo subdir in dirs)
            {
                // Create the subdirectory.
                string temppath = Path.Combine(destDirName, subdir.Name);

                // Copy the subdirectories.
                DirectoryCopy(subdir.FullName, temppath, copySubDirs);
            }
        }
    }
}

From MSDN

这篇关于在C#中文件夹复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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