/// <summary> 获取文件Hash,返回 “文件长度|文件MD5”,出错的话返回 "-1" /// </summary> /// <param name="fileName">文件全名</param> /// <returns></returns> public string GetFileHashValue(string fileName) { string fileHash = string.Empty; try { using (FileStream fileStream = new FileStream(fileName, FileMode.Open)) { try { if (fileStream.Length > 0) { string md5Val = CommFunction.GetMD5HashFromFile(fileStream); fileHash = fileStream.Length + "|" + md5Val; } } finally { fileStream.Close(); } } } catch (Exception) { fileHash = "-1"; } return(fileHash); }
private void btnViewFileNameList_Click(object sender, EventArgs e) { try { UIInProcess(true); FileProcessBaseClass fileProcBase = new FileProcessBaseClass(); fileProcBase.SetFileSelectParm(this.GetFormFileSelParm()); string fileList = fileProcBase.LoadFileList(); UIInProcess(false); if (fileList.Length > 0) { using (formTextMessage frmMessage = new formTextMessage("文件列表预览", fileList, true)) { frmMessage.ShowDialog(this); } } } catch (Exception ex) { CommFunction.WriteMessage(ex.Message); } finally { UIInProcess(false); } }
private void btnChgNmExecute_Click(object sender, EventArgs e) { new System.Threading.Thread(() => { try { UIInProcess(true); FileBatchChangeName fileBatchChangeName = ConstructFileBatchChangeName(); fileBatchChangeName.ExecuteChangeName(); SaveConfig(); } catch (Exception ex) { CommFunction.WriteMessage(ex.Message); } finally { UIInProcess(false); } GC.Collect(); } ).Start(); }
/// <summary>删除空文件夹 /// </summary> /// <param name="emptyFolderList">指定需要删除的文件夹列表</param> /// <returns></returns> public int Execute_DeleteEmptyFolder(List <string> emptyFolderList = null) { int delCount = 0; if (emptyFolderList == null) { emptyFolderList = this.GetEmptyFolderList(this.FileSelParm.SourceFileFolder, this.FileSelParm.FileFilter); } try { foreach (string dic in emptyFolderList.Where(Directory.Exists)) { Directory.Delete(dic, true); delCount++; } } catch (Exception ex) { CommFunction.WriteMessage(ex.Message); } if (delCount > 0) { CommFunction.WriteMessage(string.Format("成功删除 {0} 个空文件夹。", delCount)); } if (emptyFolderList.Count > delCount) { CommFunction.WriteMessage(string.Format("{0} 个文件夹未能正确删除。", emptyFolderList.Count - delCount)); } return(delCount); }
private void btnSpFunFindNotInTargetPathFileByFileName_Click(object sender, EventArgs e) { try { UIInProcess(true); FileSporadicFunction sporadicFunction = new FileSporadicFunction(txtConsole); sporadicFunction.SetFileSelectParm(this.GetFormFileSelParm()); string fileNames = sporadicFunction.Execute_FindNotInTargetPathFileByFileName(); if (fileNames.Length > 0) { using (formTextMessage frmMessage = new formTextMessage("找到的文件列表", fileNames, true)) { frmMessage.ShowDialog(this); } } else { CommFunction.WriteMessage("没有找到此类文件。"); } UIInProcess(false); } catch (Exception ex) { CommFunction.WriteMessage(ex.Message); } finally { UIInProcess(false); } }
public void ExecuteChangeName() { List <string> targetNameList = GetTargetNameList(); if (targetNameList.Count > 0) { string sourceFolder = (AllFile[0].DirectoryName + "\\").Replace("\\\\", "\\"); int successCnt = 0; for (int i = 0; i < targetNameList.Count; i++) { try { AllFile[i].MoveTo(sourceFolder + targetNameList[i]); successCnt++; } catch (Exception ex) { CommFunction.WriteMessage(ex.Message); } } if (successCnt > 0) { CommFunction.WriteMessage(string.Format("成功更改{0}个文件名.", successCnt)); } } else { CommFunction.WriteMessage("没有可更名的文件!"); } }
public virtual string LoadFileListAllTree(bool sortFileList = true) { string retVal = string.Empty; if (Directory.Exists(FileSelParm.SourceFileFolder)) { AllFile.Clear(); _dicRecordDate.Clear(); List <string> filterList = FileSelParm.FileFilter.ToUpper().Split('|').ToList(); bool havAllFilter = filterList.Contains("*"); bool typeIgnore = FileSelParm.FileTypeIsIgnore; DirectoryInfo dicInfo = new DirectoryInfo(FileSelParm.SourceFileFolder); this.LoadFileListAllTree(dicInfo, filterList, havAllFilter, typeIgnore); //排序 if (sortFileList) { this.SortFileList(); } //一行一行显示文件名 retVal = CommFunction.StringList2String(AllFile.Select(f => f.FullName).ToList()); } else { CommFunction.WriteMessage("文件夹不存在!"); } return(retVal); }
private void btnChgNmViewChgFileNameList_Click(object sender, EventArgs e) { try { UIInProcess(true); FileBatchChangeName fileBatchChangeName = ConstructFileBatchChangeName(); List <string> targetNameList = fileBatchChangeName.GetTargetNameList(); UIInProcess(false); if (targetNameList.Count > 0) { string nameAll = targetNameList.Aggregate("", (current, name) => current + name + Environment.NewLine).TrimEnd(Environment.NewLine.ToCharArray()); using (formTextMessage frmMessage = new formTextMessage("更名列表预览", nameAll, true)) { frmMessage.ShowDialog(this); } } } catch (Exception ex) { CommFunction.WriteMessage(ex.Message); } finally { UIInProcess(false); } }
private void LoadConfig() { try { txtSourceFolder.Text = SysConfig.GetConfigData("AppConfig", "SourceFolder", ""); txtTargetFolder.Text = SysConfig.GetConfigData("AppConfig", "TargetFolder", ""); } catch (Exception ex) { CommFunction.WriteMessage(ex.Message); } }
private void SaveConfig() { try { SysConfig.WriteConfigData("AppConfig", "SourceFolder", txtSourceFolder.Text); SysConfig.WriteConfigData("AppConfig", "TargetFolder", txtTargetFolder.Text); } catch (Exception ex) { CommFunction.WriteMessage(ex.Message); } }
private void btnSpFunDeleteEmptyFolder_Click(object sender, EventArgs e) { try { UIInProcess(true); FileSporadicFunction sporadicFunction = new FileSporadicFunction(); FileSelectParm fileSelParm = this.GetFormFileSelParm(); if (fileSelParm.FileFilter == "*") { MessageBox.Show("删除空文件夹时不能忽略所有文件。", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { sporadicFunction.SetFileSelectParm(fileSelParm); List <string> emptyFolderList = sporadicFunction.GetEmptyFolderList(fileSelParm.SourceFileFolder, fileSelParm.FileFilter); emptyFolderList.Reverse(); StringBuilder sbMsg = new StringBuilder(); foreach (string empFolder in emptyFolderList) { sbMsg.AppendLine(empFolder); } if (emptyFolderList.Count > 0) { using (formTextMessage frmMessage = new formTextMessage("是否删除以下空文件夹?", sbMsg.ToString().Trim().TrimEnd(Environment.NewLine.ToArray()), true)) { if (frmMessage.ShowDialog(this) == DialogResult.OK) { emptyFolderList.Reverse(); //重新倒置,使从子目录开始删 sporadicFunction.Execute_DeleteEmptyFolder(emptyFolderList); } } } else { CommFunction.WriteMessage("没有找到空文件夹。"); } } UIInProcess(false); } catch (Exception ex) { CommFunction.WriteMessage(ex.Message); } finally { UIInProcess(false); } }
private void btnSpFunFindMisplacedPhoto_Click(object sender, EventArgs e) { try { UIInProcess(true); FileSporadicFunction sporadicFunction = new FileSporadicFunction(); FileSelectParm fileSelParm = this.GetFormFileSelParm(); if (fileSelParm.FileFilter == string.Empty) { fileSelParm.FileFilter = CommDefinition.ExtensionPicFile; } sporadicFunction.SetFileSelectParm(fileSelParm); StringBuilder sbMsg = new StringBuilder(); List <string> fileInWrongFolder = sporadicFunction.Execute_GetFileInWrongFolder(); foreach (string fName in fileInWrongFolder) { sbMsg.AppendLine(fName); } if (fileInWrongFolder.Count > 0) { using (formTextMessage frmMessage = new formTextMessage("找到的文件列表", sbMsg.ToString().Trim().TrimEnd(Environment.NewLine.ToArray()), true)) { frmMessage.ShowDialog(this); } } else { CommFunction.WriteMessage("没有找到此类文件。"); } UIInProcess(false); } catch (Exception ex) { CommFunction.WriteMessage(ex.Message); } finally { UIInProcess(false); } }
public string Execute_FindNotInTargetPathFileByFileName() { //加载所有文件 CommFunction.WriteMessage("正在加载源文件列表...", isWrap: false); List <string> lstAllSourceFileName = base.LoadFileNameListAllTree(FileSelParm.SourceFileFolder, false); CommFunction.WriteMessage(string.Format("(完成) 总共 {0} 个文件", lstAllSourceFileName.Count), addTime: false); CommFunction.WriteMessage("正在加载目标文件列表...", isWrap: false); List <string> lstAllTargetFileName = base.LoadFileNameListAllTree(FileSelParm.TargetFileFolder, false); CommFunction.WriteMessage(string.Format("(完成) 总共 {0} 个文件", lstAllTargetFileName.Count), addTime: false); StringBuilder retSb = new StringBuilder(); foreach (string fName in lstAllSourceFileName.Where(s => !lstAllTargetFileName.Contains(s))) { retSb.AppendLine(fName); } return(retSb.ToString().TrimEnd(Environment.NewLine.ToCharArray())); }
public void Execute() { int count = 0; string sourceFolder = FileSelParm.SourceFileFolder; string origTargetFolder = FileSelParm.TargetFileFolder; string targetFolder; string dupFileFolder; //重复文件放的文件夹 bool havDupFileFolder = false; DateTime fileDate; Dictionary <string, string> moveFileList = new Dictionary <string, string>(); if (Directory.Exists(origTargetFolder)) { CommFunction.WriteMessage("目标文件夹不存在!"); return; } if (!origTargetFolder.EndsWith("\\")) { origTargetFolder = origTargetFolder + "\\"; } dupFileFolder = origTargetFolder + "Duplicate files\\"; base.AllFile.Clear(); if (base.LoadFileList().Length > 0) { //Load to moveFileList foreach (FileInfo fileInfo in base.AllFile) { //隐藏文件和系统文件就不要过来凑热闹了 if ( /*( fileInfo.Attributes & FileAttributes.Hidden ) == FileAttributes.Hidden || */ (fileInfo.Attributes & FileAttributes.System) == FileAttributes.System) { continue; } } } }
/// <summary>返回文件目录及其子目录下的所有文件 /// </summary> /// <param name="fileFolder">文件目录</param> /// <param name="returnFullName">是否返回 FullName</param> /// <returns></returns> public virtual List <string> LoadFileNameListAllTree(string fileFolder, bool returnFullName) { List <string> foundList = new List <string>(); if (Directory.Exists(fileFolder)) { AllFile.Clear(); _dicRecordDate.Clear(); List <string> filterList = FileSelParm.FileFilter.ToUpper().Split('|').ToList(); bool havAllFilter = filterList.Contains("*"); bool typeIgnore = FileSelParm.FileTypeIsIgnore; DirectoryInfo dicInfo = new DirectoryInfo(fileFolder); this.LoadFileNameListAllTree(dicInfo, filterList, havAllFilter, typeIgnore, foundList, returnFullName); } else { CommFunction.WriteMessage("文件夹不存在!"); } foundList.Reverse(); return(foundList); }
public string Execute_FindNotInTargetPathFileByContent(bool genCopyCmd = false) { //加载所有文件 CommFunction.WriteMessage("正在加载源文件列表...", isWrap: false); List <string> lstAllSourceFileName = base.LoadFileNameListAllTree(FileSelParm.SourceFileFolder, true); CommFunction.WriteMessage(string.Format("(完成) 总共 {0} 个文件", lstAllSourceFileName.Count), addTime: false); CommFunction.WriteMessage("正在加载目标文件列表...", isWrap: false); List <string> lstAllTargetFileName = base.LoadFileNameListAllTree(FileSelParm.TargetFileFolder, true); CommFunction.WriteMessage(string.Format("(完成) 总共 {0} 个文件", lstAllTargetFileName.Count), addTime: false); //算出Hash,填充序列 CommFunction.WriteMessage("正在计算文件Hash值...", isWrap: false); StringBuilder errText = new StringBuilder(); //获取文件Hash,在此方法中,出错的话,Hash随机取 "-1" Func <string, string> getFileHashValue = delegate(string fName) { string fileHash = GetFileHashValue(fName); if (fileHash == "-1") { errText.AppendLine(string.Format("文件计算Hash出错。{0}", fName)); } return(fileHash); }; // 异步获取目标文件夹文件的Hash List <string> targHashList = lstAllTargetFileName.AsParallel().Select(getFileHashValue).Where(hash => hash != "-1").ToList(); // 异步获取源文件夹文件的Hash List <Tuple <string, string> > sourceHashList = lstAllSourceFileName.AsParallel().Select(fName => Tuple.Create(fName, getFileHashValue(fName))).Where(fh => fh.Item2 != "-1").ToList(); CommFunction.WriteMessage("(完成) ", addTime: false); if (errText.Length > 0) { base.FormConsoleTextBox.Text = base.FormConsoleTextBox.Text + errText; } List <string> foundList = sourceHashList.Where(t => !targHashList.Contains(t.Item2)).Select(t => t.Item1).ToList(); foundList.Sort(); StringBuilder retSb = new StringBuilder(); if (genCopyCmd) { const string copyFormat = "copy \"{0}\" \"{1}\""; foreach (string fName in foundList) { retSb.AppendLine(string.Format(copyFormat, fName, FileSelParm.TargetFileFolder)); } } else { foreach (string fName in foundList) { retSb.AppendLine(fName); } } return(retSb.ToString().TrimEnd(Environment.NewLine.ToCharArray())); }
private void btnTest_Click(object sender, EventArgs e) { CommFunction.WriteMessage("abc", isWrap: false); //Console.Write("abc"); CommFunction.BackspaceInConsole("bc", txtConsole); }
public virtual string LoadFileList() { string retVal = string.Empty; if (Directory.Exists(FileSelParm.SourceFileFolder)) { AllFile.Clear(); DicRecordDate.Clear(); List <string> filterList = FileSelParm.FileFilter.ToUpper().Split('|').ToList(); bool havAllFilter = filterList.Contains("*"); DirectoryInfo dicInfo = new DirectoryInfo(FileSelParm.SourceFileFolder); List <string> chgFileList = FileSelParm.UseSpecFileList ? FileSelParm.SpecFileList.ToUpper().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList() : null; foreach (FileInfo fileInfo in dicInfo.GetFiles()) { if (FileSelParm.UseSpecFileList) { if (chgFileList != null && chgFileList.Contains(fileInfo.Name.ToUpper())) { AllFile.Add(fileInfo); } } else { if (havAllFilter) { AllFile.Add(fileInfo); } else { string strExt = fileInfo.Extension.Remove(0, 1).ToUpper(); if (filterList.Contains(strExt)) { AllFile.Add(fileInfo); } } } } //排序 switch (FileSelParm.FileSortBy) { case FileSortMode.FileName: AllFile.Sort((x, y) => String.Compare(x.Name, y.Name, StringComparison.Ordinal)); break; case FileSortMode.CreateDate: AllFile.Sort((x, y) => DateTime.Compare(x.CreationTime, y.CreationTime)); break; case FileSortMode.ModifyDate: AllFile.Sort((x, y) => DateTime.Compare(x.LastWriteTime, y.LastWriteTime)); break; case FileSortMode.RecordingDate: //直接取拍摄日期,文件多了会内存溢出 foreach (FileInfo fileInfo in AllFile) { DicRecordDate.Add(fileInfo.FullName, CommFunction.GetFileDateTime(fileInfo, true)); GC.Collect(); } //_allFile.Sort((x, y) => DateTime.Compare(CommFunction.GetFileDateTime(x, true), CommFunction.GetFileDateTime(y, true))); AllFile.Sort((x, y) => DateTime.Compare(DicRecordDate[x.FullName], DicRecordDate[y.FullName])); break; default: throw new ArgumentOutOfRangeException(); } //一行一行显示文件名 StringBuilder sbFilenames = new StringBuilder(); foreach (FileInfo fileInfo in AllFile) { sbFilenames.AppendLine(fileInfo.Name); } retVal = sbFilenames.ToString().TrimEnd(Environment.NewLine.ToCharArray()); } else { CommFunction.WriteMessage("文件夹不存在!"); } return(retVal); }
public void Execute() { int count = 0; string sourceFolder = FileSelParm.SourceFileFolder; string origTargetFolder = FileSelParm.TargetFileFolder; string targetFolder, targetFileFullName; string dupFileFolder; //重复文件放的文件夹 bool havDupFileFolder = false; DateTime fileDate; Dictionary <string, string> moveFileList = new Dictionary <string, string>(); try { base.BeforeExecute(); if (!Directory.Exists(sourceFolder)) { CommFunction.WriteMessage("源文件夹不存在!"); return; } if (!Directory.Exists(origTargetFolder)) { CommFunction.WriteMessage("目标文件夹不存在!"); return; } if (!origTargetFolder.EndsWith("\\")) { origTargetFolder = origTargetFolder + "\\"; } dupFileFolder = origTargetFolder + "Duplicate files\\"; if (base.LoadFileList(false).Length > 0) { //create and record file target foreach (FileInfo origFile in base.AllFile) { fileDate = base.GetFileDate(origFile, base.DatePriority); targetFolder = origTargetFolder + fileDate.ToString("yyyy-MM-dd") + "\\"; if (!Directory.Exists(targetFolder)) { Directory.CreateDirectory(targetFolder); } if (File.Exists(targetFolder + origFile.Name)) { if (!havDupFileFolder || !Directory.Exists(dupFileFolder)) { Directory.CreateDirectory(dupFileFolder); havDupFileFolder = true; } targetFileFullName = dupFileFolder + origFile.Name; } else { targetFileFullName = targetFolder + origFile.Name; } moveFileList.Add(origFile.FullName, targetFileFullName); } base.AllFile.Clear(); GC.Collect(); foreach (KeyValuePair <string, string> fileNamePare in moveFileList) { if (this.MoveFile) { File.Move(fileNamePare.Key, fileNamePare.Value); } else { File.Copy(fileNamePare.Key, fileNamePare.Value, true); } count++; } if (this.MoveFile) { CommFunction.WriteMessage("移动完成! 共 " + count + " 个文件。"); } else { CommFunction.WriteMessage("复制完成! 共 " + count + " 个文件。"); } } } catch (Exception ex) { CommFunction.WriteMessage(ex.Message); CommFunction.WriteMessage("已处理完成文件共 " + count + " 个。"); } }
/// <summary>按内容查找重复文件 /// </summary> /// <returns></returns> public string Execute_FindDuplicateFilesByContent() { Dictionary <string, List <string> > foundList = new Dictionary <string, List <string> >(); //加载所有文件 CommFunction.WriteMessage("正在加载文件列表...", isWrap: false); List <string> lstAllFileName = base.LoadFileNameListAllTree(FileSelParm.SourceFileFolder, true); CommFunction.WriteMessage(string.Format("(完成) 总共 {0} 个文件", lstAllFileName.Count), addTime: false); //算出Hash,填充序列 CommFunction.WriteMessage("正在计算文件Hash值...", isWrap: false); StringBuilder errText = new StringBuilder(); //获取文件Hash,在此方法中,出错的话,Hash随机取 "-1" Func <string, string> getFileHashValue = delegate(string fName) { string fileHash = GetFileHashValue(fName); if (fileHash == "-1") { errText.AppendLine(string.Format("文件计算Hash出错。{0}", fName)); } return(fileHash); }; //异步获取所有文件的Hash ParallelQuery <Tuple <string, string> > fileHashs = lstAllFileName.AsParallel().Select(fName => Tuple.Create(fName, getFileHashValue(fName))).Where(fh => fh.Item2 != "-1"); foreach (Tuple <string, string> fileHash in fileHashs) { //创建/更新哈希列表组 if (foundList.ContainsKey(fileHash.Item2)) { foundList[fileHash.Item2].Add(fileHash.Item1); } else { foundList.Add(fileHash.Item2, new List <string>(new[] { fileHash.Item1 })); } } //此为同步版本,可显示百分比 /* * float fileIndex = 0; * foreach (string fName in lstAllFileName) { * fileIndex++; * int percent = (int)( fileIndex / lstAllFileName.Count * 100 ); * string msgText = string.Format("({0}%) {1}", percent, fName); * CommFunction.WriteMessage(msgText, isWrap: false, addTime: false); * * try { * using (FileStream fileStream = new FileStream(fName, FileMode.Open)) { * try { * if (fileStream.Length > 0) { * string md5Val = CommFunction.GetMD5HashFromFile(fileStream); * string fileHash = fileStream.Length + "|" + md5Val; * * //创建/更新哈希列表组 * if (foundList.ContainsKey(fileHash)) * foundList[fileHash].Add(fName); * else * foundList.Add(fileHash, new List<string>(new[] {fName})); * } * } * finally { * fileStream.Close(); * } * } * } * catch (Exception ex) { * errText.AppendLine(ex.Message); * } * * CommFunction.BackspaceInConsole(msgText, base.FormConsoleTextBox); * } */ CommFunction.WriteMessage("(完成) ", addTime: false); if (errText.Length > 0) { //CommFunction.WriteMessage(errText.ToString(), addTime: false); base.FormConsoleTextBox.Text = base.FormConsoleTextBox.Text + errText; } StringBuilder retSb = new StringBuilder(); //取数量大于1的为相同的文件 foreach (KeyValuePair <string, List <string> > foundGroup in foundList.Where(fl => fl.Value.Count > 1)) { //倒置列表以符合常规文件排序 foundGroup.Value.Reverse(); foreach (string fName in foundGroup.Value) { retSb.AppendLine(fName); } retSb.AppendLine(); //每组加一空行 } return(retSb.ToString().TrimEnd(Environment.NewLine.ToCharArray())); }
public virtual string LoadFileList(bool sortFileList = true) { string retVal = string.Empty; if (Directory.Exists(FileSelParm.SourceFileFolder)) { AllFile.Clear(); _dicRecordDate.Clear(); List <string> filterList = FileSelParm.FileFilter.ToUpper().Split('|').ToList(); bool havAllFilter = filterList.Contains("*"); bool typeIgnore = FileSelParm.FileTypeIsIgnore; DirectoryInfo dicInfo = new DirectoryInfo(FileSelParm.SourceFileFolder); List <string> chgFileList = FileSelParm.UseSpecFileList ? FileSelParm.SpecFileList.ToUpper().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList() : null; foreach (FileInfo fileInfo in dicInfo.GetFiles()) { //隐藏文件和系统文件就不要过来凑热闹了 if ( /*( fileInfo.Attributes & FileAttributes.Hidden ) == FileAttributes.Hidden || */ (fileInfo.Attributes & FileAttributes.System) == FileAttributes.System) { continue; } if (FileSelParm.UseSpecFileList) { if (chgFileList != null && chgFileList.Contains(fileInfo.Name.ToUpper())) { AllFile.Add(fileInfo); } } else { if (havAllFilter && !typeIgnore) { AllFile.Add(fileInfo); } else { string strExt = fileInfo.Extension.Length > 0 ? fileInfo.Extension.Remove(0, 1).ToUpper() : ""; //符合异或条件 if (typeIgnore ^ filterList.Contains(strExt)) { AllFile.Add(fileInfo); } } } } //排序 if (sortFileList) { this.SortFileList(); } //一行一行显示文件名 retVal = CommFunction.StringList2String(AllFile.Select(f => f.FullName).ToList()); } else { CommFunction.WriteMessage("文件夹不存在!"); } return(retVal); }