????????在Unity游戲開發(fā)中腹纳,有時候做編輯器開發(fā)源葫,或者做一些小工具的時候經(jīng)常用到文件操作诗越。文件夾內(nèi)容的復制是最常用的,這里做個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函數(shù)實現(xiàn)了荣堰,遞歸拷貝源文件夾下面的所有文件到目標文件床未。
2、如果目標文件已存在同名文件振坚,會進行覆蓋處理薇搁,如果有不想覆蓋情況,請自行處理屡拨。
3只酥、createSrcFolder_字段來判斷是否要創(chuàng)建源文件夾,然后在拷貝呀狼。有些時候裂允,我只想拷貝源文件夾下面的所有文件,但是不包括這個源文件夾自身哥艇,就可以把這個字段設(shè)置為false绝编,否則會把源文件夾一起拷貝到目標文件下面,作為其子文件夾貌踏。