//断言 private static bool Assert(SearchConfig searchConfig, StringBuilder result) { if (searchConfig == null) { result.AppendLine("查找配置不能为空."); return(false); } if (searchConfig.Find == null || searchConfig.Find.Count <= 0) { result.AppendLine("查找内容不能为空."); return(false); } if (!Directory.Exists(searchConfig.Config.WorkDir)) { result.AppendLine("工作目录不存在."); return(false); } return(true); }
//替换 public static int Replace(IWin32Window owner, SearchConfig searchConfig, StringBuilder result) { if (!Assert(searchConfig, result)) { return(0); } int count = 0; List <string> affects = new List <string>(); using (FrmBatch <FileInfo> dialog = new FrmBatch <FileInfo>(10)) { dialog.Text = "正在执行查找替换操作"; //工作 dialog.Work += delegate(object sender, EventArgs <FileInfo> e) { FileInfo fileInfo = e.Argument; if (fileInfo == null) { return; } string fullName; string oldText = File.ReadAllText(fullName = fileInfo.FullName, Encoding.UTF8); string newText = oldText; StringComparison comparison = searchConfig.CaseMatch ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; //大小写 if (searchConfig.WordMatch) //全字 { searchConfig.Find.ForEach(find => newText = newText.ReplaceWord(find.Key, find.Value, comparison)); } else { searchConfig.Find.ForEach(find => newText = newText.Replace(find.Key, find.Value, comparison)); } if (newText != oldText) { searchConfig.Config.CheckOut(fileInfo); fileInfo.IsReadOnly = false;//去掉只读属性 File.WriteAllText(fullName, newText, Encoding.UTF8); lock (affects) affects.Add(fullName); dialog.WriteLog("替换 {0}", fullName); } }; //全部完成,统计 dialog.AllWorkComplete += delegate(object sender, EventArgs e) { count = affects.Count; affects.OrderBy(fullName => fullName).ForEach(fullName => result.AppendLine(fullName)); }; //入队 foreach (FileInfo fileInfo in new DirectoryInfo(searchConfig.Config.WorkDir).VisitFilesByShortPattern(searchConfig.FileUseWildcard ? searchConfig.FileWildcard : null))//通配符 { dialog.Enqueue(fileInfo); } //显示 dialog.ShowDialog(owner); } return(count); }
//生成查询参数 private SearchConfig GenSearchConfig() { return(new SearchConfig(this.chkUseWildCard.Checked, this.txtWildcard.Text, this.chkCaseMatch.Checked, this.chkWordMatch.Checked, this.rbtnMultiLine.Checked ? SearchConfig.GenFindReplace(this.txtTop.Text, this.txtBottom.Text) : SearchConfig.GenFindReplace(this.txtTop.Text))); }