using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; /******************************************************************************* *Create By CG *Function 对文件进行操作 *******************************************************************************/ namespace CG.UTility { public static class FileHandle { /// /// 创建文件夹 /// /// 文件夹路径 public static void CreateFolder(string folderPath) { if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } } /// /// 查看路径下是否有此文件,如果已经有了,则在次基础上文件名加1,或者将原有的删除 /// 如果保留重复文件有逻辑问题,待修复 /// /// /// 如果已经有此文件了,是否删除旧文件 /// public static string CheckFile(string filePath,bool delOld=false) { string folderPath = Path.GetDirectoryName(filePath); string fileName = Path.GetFileName(filePath); DirectoryInfo dinfo = new DirectoryInfo(folderPath); FileInfo[] sameFiles = dinfo.GetFiles(fileName, SearchOption.TopDirectoryOnly); if (sameFiles.Length > 0) { if (delOld) { File.Delete(filePath); return filePath; } else { string fileNewName = Path.GetFileNameWithoutExtension(filePath) + $"({sameFiles.Length})"; string fileExtension = Path.GetExtension(filePath); string fileNewPath = folderPath + "/" + fileNewName + fileExtension; return fileNewPath; } } else { return filePath; } } /// /// 文件创建,如果原来有此文件,则直接覆盖 /// /// 创建文件路径,eg:D:\Unity\Editor\test.txt public static void CreateFile(string filePath) { try { string folderPath = Path.GetDirectoryName(filePath); CreateFolder(folderPath); FileInfo file = new FileInfo(filePath); //创建文件 FileStream fs = file.Create(); //关闭文件流 fs.Close(); } catch (System.Exception ex) { WDebug.LogError("CreateFile Erro :" + ex.Message); return; } } /// /// 根据字节流创建文件 /// /// /// public static void CreateFile(string filePath, byte[] fileContain) { try { string folderPath = Path.GetDirectoryName(filePath); CreateFolder(folderPath); File.WriteAllBytes(filePath, fileContain); } catch (System.Exception ex) { WDebug.LogError("CreateFile Erro :" + ex.Message); return; } } /// /// 文件删除 /// /// 文件路径 public static bool DelFile(string filePath) { try { if (File.Exists(filePath)) { File.Delete(filePath); return true; } else { WDebug.LogWarning("DelFile Warn :文件不存在"); return false; } } catch (System.Exception ex) { WDebug.LogError("CopyFile Erro :" + ex.Message); return false; } } /// /// 文件复制 /// /// 文件原始路径 /// 文件复制目标路径 /// 如果在目标文件中存在相同文件是否替换 public static void CopyFile(string originFilePath,string targetFilePath,bool replace) { try { File.Copy(originFilePath, targetFilePath, replace); } catch (System.Exception ex) { WDebug.LogError("CopyFile Erro :" + ex.Message); return; } } /// /// 文件移动 /// /// 文件原始路径 /// 文件移动目标路径 /// 如果在目标文件中存在相同文件是否覆盖 public static void MoveFile(string originFilePath, string targetFilePath, bool cover) { try { if (File.Exists(targetFilePath)&& cover) { File.Delete(targetFilePath); } File.Move(originFilePath, targetFilePath); } catch (System.Exception ex) { WDebug.LogError("CopyFile Erro :" + ex.Message); return; } } } }