private void ReplaceDirectory(ReplaceOptions option, string path) { if (Directory.Exists(path)) { var dirInfo = new DirectoryInfo(path); var files = dirInfo.GetFiles(); //替换文件以及内容 foreach (var item in files) { ReplaceFile(option, item.FullName); } //替换子目录以及子目录文件 var dirs = dirInfo.GetDirectories(); foreach (var item in dirs) { var target = Path.Combine(item.Parent.FullName, Replace(option, item.Name)); if (item.FullName != target) { item.MoveTo(target); } ReplaceDirectory(option, item.FullName); } } else { Console.WriteLine("路径:" + path + "不存在!"); } }
/// <summary> /// 替换内容 /// </summary> /// <param name="option"></param> /// <param name="text"></param> /// <returns></returns> private string Replace(ReplaceOptions option, string text) { for (int i = 0; i < SourceArray.Length; i++) { text = text.Replace(SourceArray[i], TargetArray[i]); } return(text); }
//重命名文件以及替换文件内容 private void ReplaceFile(ReplaceOptions option, string path) { if (option.IsReplaceText) { var content = File.ReadAllText(path); content = Replace(option, content); File.WriteAllText(path, content); } var fileName = Path.GetFileName(path); fileName = Replace(option, fileName); var target = Path.Combine(Path.GetDirectoryName(path), fileName); if (path != target) { File.Move(path, target); } }