C# 文件夹递归拷贝操作

        在Unity游戏开发中,有时候做编辑器开发,或者做一些小工具的时候经常用到文件操作。文件夹内容的复制是最常用的,这里做个Mark,方便以后翻阅,同时也能分享给那些需要同样接口的筒靴们(别问我为什么不用Unity自带的文件操作(UnityEditor.FileUtil))

上菜(code):

using System.Collections;

using System.Collections.Generic;

using System.IO;

using UnityEngine;

public class Scripts : MonoBehaviour

{

    string srcPath;

    string dstPath;

    // Use this for initialization

    void Start()

    {

        srcPath = Application.dataPath + "/../TestSrc";

        dstPath = Application.dataPath + "/../TestDst";

        CopyFolder(srcPath, dstPath, false);

    }

    void CopyFolder(string srcPath_, string dstPath_, bool createSrcFolder_ = true)

    {

        string symbol1 = "/";

        string symbol2 = "\\";

        if(createSrcFolder_)

        {

            string strFolderName = srcPath_.Substring(srcPath_.LastIndexOf(symbol1) + 1, srcPath_.Length - srcPath_.LastIndexOf(symbol1) - 1);

            dstPath_ = dstPath_ + symbol1 + strFolderName;

            if (!Directory.Exists(dstPath_) && createSrcFolder_)

            {

                Directory.CreateDirectory(dstPath_);

            }

        }

        string[] strFiles = Directory.GetFiles(srcPath_);

        foreach (string filePath in strFiles)

        {

            string strFileName = filePath.Substring(filePath.LastIndexOf(symbol2) + 1, filePath.Length - filePath.LastIndexOf(symbol2) - 1);

            string dstAddress = dstPath_ + symbol1 + strFileName;

            File.Copy(filePath, dstAddress, true);

        }

        DirectoryInfo dirInfo = new DirectoryInfo(srcPath_);

        DirectoryInfo[] dirPaths = dirInfo.GetDirectories();

        foreach (var dirPath in dirPaths)

        {

            CopyFolder(srcPath_ + symbol1 + dirPath.Name, dstPath_);

        }

    }

}

代码简单介绍:

1、CopyFolder函数实现了,递归拷贝源文件夹下面的所有文件到目标文件。

2、如果目标文件已存在同名文件,会进行覆盖处理,如果有不想覆盖情况,请自行处理。

3、createSrcFolder_字段来判断是否要创建源文件夹,然后在拷贝。有些时候,我只想拷贝源文件夹下面的所有文件,但是不包括这个源文件夹自身,就可以把这个字段设置为false,否则会把源文件夹一起拷贝到目标文件下面,作为其子文件夹。

你可能感兴趣的:(C# 文件夹递归拷贝操作)