From 8b55373794f178c60944a464586d619dc620ead1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E6=B7=B3?= Date: Tue, 3 Jan 2023 16:03:11 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=96=87=E4=BB=B6helper?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Yi.Framework.Common/Helper/FileHelper.cs | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/Yi.Framework.Net6/Yi.Framework.Common/Helper/FileHelper.cs b/Yi.Framework.Net6/Yi.Framework.Common/Helper/FileHelper.cs index 4e13d382..7ae1c0c4 100644 --- a/Yi.Framework.Net6/Yi.Framework.Common/Helper/FileHelper.cs +++ b/Yi.Framework.Net6/Yi.Framework.Common/Helper/FileHelper.cs @@ -407,6 +407,84 @@ namespace Yi.Framework.Common.Helper return folder.Select(x => x.Name).ToList(); } + /// + /// 文件内容替换 + /// + public static string FileContentReplace(string path, string oldStr, string newStr) + { + var content = File.ReadAllText(path); + if (content.Contains(oldStr)) + { + File.Delete(path); + File.WriteAllText(path, content.Replace(oldStr, newStr)); + } + + return path; + } + /// + /// 文件名称 + /// + public static string FileNameReplace(string path, string oldStr, string newStr) + { + string fileName = Path.GetFileName(path); + if (!fileName.Contains(oldStr)) + { + return path; + } + + string? directoryName = Path.GetDirectoryName(path); + string newFileName = fileName.Replace(oldStr, newStr); + string newPath = Path.Combine(directoryName ?? "", newFileName); + File.Move(path, newPath); + + return newPath; + } + /// + /// 目录名替换 + /// + public static string DirectoryNameReplace(string path, string oldStr, string newStr) + { + string fileName = Path.GetFileName(path); + if (!fileName.Contains(oldStr)) + { + return path; + } + + string? directoryName = Path.GetDirectoryName(path); + string newFileName = fileName.Replace(oldStr, newStr); + string newPath = Path.Combine(directoryName ?? "", newFileName); + Directory.Move(path, newPath); + return newPath; + } + + /// + /// 全部信息递归替换 + /// + /// + /// + /// + public static void AllInfoReplace(string dirPath, string oldStr, string newStr) + { + var path = DirectoryNameReplace(dirPath, oldStr, newStr); + var dirInfo = new DirectoryInfo(path); + var files = dirInfo.GetFiles(); + var dirs = dirInfo.GetDirectories(); + if (files.Length > 0) + { + foreach (var f in files) + { + FileContentReplace(f.FullName, oldStr, newStr); + FileNameReplace(f.FullName, oldStr, newStr); + } + } + if (dirs.Length > 0) + { + foreach (var d in dirs) + { + AllInfoReplace(d.FullName, oldStr, newStr); + } + } + } } }