自动替换文件内容、文件名、文件夹名
作者:互联网
void Main() { var root = @"c:\smartcampus-submodule\zhzp"; //var extensions = string.Join("," ,getFileExtensions(root)); //extensions.Dump(); replaceFilesContent(root, "dygl", "zhzp",".iml,.xml,.txt,.java,.properties,.lst,.json,.yml,.map"); replaceFileNames(root, "dygl", "zhzp"); replaceFolderNames(root, "dygl", "zhzp"); } List<string> getFileExtensions(string folder) { var result = new List<string>(); var dir = new DirectoryInfo(folder); foreach (var file in dir.GetFiles()) { result = result.Union(new List<string> { file.Extension.ToLower() }).ToList(); } foreach (var subDir in dir.GetDirectories()) { result = result.Union(getFileExtensions(subDir.FullName)).ToList(); } return result; } string replaceContent(string content, string find, string replace) { if(find == "") return content; var pos = 0; while (true) { pos = content.IndexOf(find, pos, StringComparison.CurrentCultureIgnoreCase); if (pos < 0) break; var reachEnd = pos + find.Length >= content.Length; var foundContent = content.Substring(pos, find.Length); var destReplace = replace ; if (foundContent[0].ToString().ToUpper() == foundContent[0].ToString() && replace.Length > 0) destReplace = replace[0].ToString().ToUpper() + replace.Substring(1); content = content.Substring(0, pos) + destReplace + (reachEnd ? "" : content.Substring(pos + find.Length)); } return content; } void replaceFilesContent(string folder, string find, string replace, string extensions) { var exts = extensions.Split(',').ToList(); var dir = new DirectoryInfo(folder); foreach (var file in dir.GetFiles()) { if (!exts.Contains(file.Extension.ToLower())) continue; var content = File.ReadAllText(file.FullName); content = replaceContent(content, find, replace); File.WriteAllText(file.FullName, content); Console.WriteLine(file.FullName + " content replaced"); } foreach (var subDir in dir.GetDirectories()) { replaceFilesContent(subDir.FullName, find, replace, extensions); } } void replaceFileNames(string folder, string find, string replace) { var dir = new DirectoryInfo(folder); foreach (var file in dir.GetFiles()) { var filename = replaceContent(file.Name, find, replace); if(filename != file.Name) { var old = file.FullName; file.MoveTo(file.Directory.FullName + "\\" + filename); Console.WriteLine(old + " renamed"); } } foreach (var subDir in dir.GetDirectories()) { replaceFileNames(subDir.FullName,find,replace); } } void replaceFolderNames(string folder, string find, string replace) { var dir = new DirectoryInfo(folder); if (dir.GetDirectories().Count() > 0) { foreach (var subDir in dir.GetDirectories()) { replaceFolderNames(subDir.FullName, find, replace); } } var dirName = replaceContent(dir.Name, find, replace); if (dirName != dir.Name) { var old = dir.FullName; dir.MoveTo(dir.Parent.FullName + "\\" + dirName); Console.WriteLine(old + " renamed"); } } // Define other methods and classes here
标签:string,文件名,find,content,文件夹,var,replace,替换,dir 来源: https://www.cnblogs.com/nanfei/p/16617349.html