private bool isImageFile(string path) { bool result = false; System.Drawing.Image image = null; System.Drawing.Graphics graphics = null; try { image = System.Drawing.Image.FromFile(path); result = true; graphics = System.Drawing.Graphics.FromImage(image); } catch (System.Exception ex) { logException(ex); FileWriterWithAppendMode.GlobalWrite(path); } finally { if (graphics != null) { graphics.Dispose(); } if (image != null) { image.Dispose(); } } return(result); }
private void DeleteDirectoryWithoutException(string directoryPath,ThreadParameters parameters) { try { FileWriterWithAppendMode.GlobalWrite(CultureStrings.TryDeleting+" "+singleQuoteText(directoryPath)); string[]subDirectories=System.IO.Directory.GetDirectories(directoryPath); foreach(string subDirectory in subDirectories) { if(!parameters.SourceDirectories.Any(sourceDirectory=>sourceDirectory.StartsWith(subDirectory))) { DeleteDirectoryWithoutException(subDirectory,parameters); } } subDirectories=System.IO.Directory.GetDirectories(directoryPath); string[]files=System.IO.Directory.GetFiles(directoryPath); if(onlyOneThumbsDbFile(files)) { deleteFileWithoutException(files[0],parameters); } files=System.IO.Directory.GetFiles(directoryPath); if(subDirectories.Length==0&&files.Length==0) { System.IO.Directory.Delete(directoryPath); FileWriterWithAppendMode.GlobalWrite(CultureStrings.TextDeleted+" "+singleQuoteText(directoryPath)); } } catch(System.Exception ex) { FileWriterWithAppendMode.GlobalWrite(CultureStrings.TextFailedInDeleting+" "+singleQuoteText(directoryPath)); logException(ex); } }
private ThreadParameters filterSourcePaths(ThreadParameters parameters) { System.Collections.Generic.List <string> sourcePaths = new System.Collections.Generic.List <string>(); if (parameters.LogFilePath_ThreadResult != null) { if (System.IO.File.Exists(parameters.LogFilePath_ThreadResult)) { sourcePaths = System.IO.File.ReadAllLines(parameters.LogFilePath_ThreadResult, System.Text.Encoding.Unicode).ToList(); } } if (sourcePaths.Count == 0) { return(parameters); } lock (copyFilesJobs) { parameters.LogFilePath_ThreadResult = buildCollectPhotoDataFilePath(parameters.DestinationRootDirectory, CultureStrings.ResultFileFilter); } FileWriterWithAppendMode logger = FileWriterWithAppendMode.Open(parameters.LogFilePath_ThreadResult); for (int i = 0; i < sourcePaths.Count; i++) { string filePath = sourcePaths[i]; if (backgroundWorker_Filter.IsBusy) { backgroundWorker_Filter.ReportProgress(calculatePercentage(sourcePaths.Count, i), filePath); } if (isMatchingFilePath(filePath, parameters.IncludeFileExtensions) || isMatchingFilePath(filePath, parameters.IncludeFileExtensionAndFileNameMap)) { logger.WriteLine(filePath); continue; } if (isMatchingFilePath(filePath, parameters.ExcludeFileExtensions) || isMatchingFilePath(filePath, parameters.IncludeFileExtensionAndFileNameMap.Keys.ToArray())) { continue; } if (isMatchingFilePath(filePath, parameters.ImageFileExtensions)) { logger.WriteLine(filePath); continue; } string extension = System.IO.Path.GetExtension(filePath); if (extension.Length == 0) { continue; } if (parameters.AutoDetermine && isImageFile(filePath)) { parameters.ImageFileExtensions = parameters.ImageFileExtensions.Concat(new string[] { extension }).ToArray(); logger.WriteLine(filePath); continue; } parameters.ExcludeFileExtensions = parameters.ExcludeFileExtensions.Concat(new string[] { extension }).ToArray(); } logger.Close(); return(parameters); }
private string getPropertyValue(string imagePath, System.Drawing.Image image, int id) { try { if (image.PropertyIdList.Contains(id)) { return(getPropertyValue(image.GetPropertyItem(id))); } else { TagLib.Image.File tagImage = TagLib.File.Create(imagePath) as TagLib.Image.File; string result = null; if (id == manufacturerId && tagImage.ImageTag.Make != null && tagImage.ImageTag.Make.Length > 0) { result = tagImage.ImageTag.Make; } else if (id == modelId && tagImage.ImageTag.Model != null && tagImage.ImageTag.Model.Length > 0) { result = tagImage.ImageTag.Model; } else if (id == dateTakenId && tagImage.ImageTag.DateTime.HasValue) { result = tagImage.ImageTag.DateTime.Value.ToString(CultureStrings.FormatDateTaken); } else if (id == dateTakenId && !tagImage.ImageTag.DateTime.HasValue) { result = getPropertyValue(image.GetPropertyItem(dateTimeId)); } else if (id == latitudeLongitudeId && tagImage.ImageTag.Latitude.HasValue && tagImage.ImageTag.Longitude.HasValue) { result = tagImage.ImageTag.Latitude + "," + tagImage.ImageTag.Longitude; } tagImage.Dispose(); if (result != null) { return(result); } else { FileWriterWithAppendMode.GlobalWrite(string.Format(CultureStrings.InfomationImageProperties, doubleQuoteText(imagePath), id, convertIntsToText(image.PropertyIdList))); } } } catch (System.Exception ex) { logException(ex); } return(null); }
private void deleteFileWithoutException(string filePath,ThreadParameters parameters) { try { System.IO.FileInfo fileInfo=new System.IO.FileInfo(filePath); if(fileInfo.IsReadOnly&¶meters.DeleteReadOnly) { fileInfo.IsReadOnly=false; } if(fileInfo.Exists) { fileInfo.Delete(); } FileWriterWithAppendMode.GlobalWrite(CultureStrings.TextDeleted+" "+singleQuoteText(filePath)); } catch(System.Exception ex) { FileWriterWithAppendMode.GlobalWrite(CultureStrings.TextFailedInDeleting+" "+singleQuoteText(filePath)); logException(ex); } }
private void getFiles(string directoryPath, string searchPattern, System.IO.SearchOption searchOption, int deepnessLimitation, ThreadParameters parameters) { FileWriterWithAppendMode.GlobalWrite(string.Format("getFiles, directory path: {0}, deepness limitation: {1}.", doubleQuoteText(directoryPath), deepnessLimitation)); string[] fileExtensions = parameters.FilterWhileSearching?parameters.ImageFileExtensions.Concat(parameters.IncludeFileExtensions).ToArray():null; string resultFilePath = parameters.LogFilePath_ThreadResult; if (backgroundWorker_Search.CancellationPending) { throw new System.Exception("Cancel getFiles!"); } if (backgroundWorker_Search.IsBusy) { backgroundWorker_Search.ReportProgress(0, directoryPath); } if (deepnessLimitation <= 0) { return; } string[] topDirectoryFiles = getFiles(directoryPath, searchPattern); if (topDirectoryFiles != null) { appendLines(resultFilePath, filterFilePaths(topDirectoryFiles, fileExtensions)); } if (searchOption == System.IO.SearchOption.AllDirectories) { string[] directories = getDirectories(directoryPath); if (directories != null) { foreach (string directory in directories) { if (isMatchingDirectoryPath(directory, parameters.BypassRegexes)) { continue; } getFiles(directory, searchPattern, searchOption, deepnessLimitation - 1, parameters); } } } }
private ThreadParameters getThreadParameters() { ThreadParameters parameters = new ThreadParameters(); parameters.SourceDirectories = stripBlankLines(richTextBox_SourceDirectories.Lines); parameters.ImageFileExtensions = stripBlankLines(richTextBox_ImageFileExtensions.Lines); parameters.ExcludeFileExtensions = stripBlankLines(richTextBox_ExcludeFileExtensions.Lines); System.Collections.Generic.List <string> includeFileExtensions = new System.Collections.Generic.List <string>(); System.Collections.Generic.List <string> includeFileNameExtensions = new System.Collections.Generic.List <string>(); foreach (string line in richTextBox_IncludeFileExtensions.Lines) { if (line.Length > 0 && fileExtensionPattern.IsMatch(line)) { includeFileExtensions.Add(line); } else { includeFileNameExtensions.Add(line); } } parameters.IncludeFileExtensions = includeFileExtensions.ToArray(); parameters.IncludeFileExtensionAndFileNameMap = new System.Collections.Generic.Dictionary <string, System.Text.RegularExpressions.Regex>(); foreach (string includeFileName in includeFileNameExtensions) { string pattern = System.IO.Path.GetFileNameWithoutExtension(includeFileName); if (pattern == "*") { includeFileExtensions.Add(System.IO.Path.GetExtension(includeFileName)); parameters.IncludeFileExtensions = includeFileExtensions.ToArray(); continue; } else if (pattern.Length == 0) { continue; } if (!parameters.IncludeFileExtensionAndFileNameMap.ContainsKey(System.IO.Path.GetExtension(includeFileName))) { parameters.IncludeFileExtensionAndFileNameMap.Add(System.IO.Path.GetExtension(includeFileName), new System.Text.RegularExpressions.Regex(pattern)); } } parameters.SearchDirectoriesBypassPatterns = stripBlankLines(richTextBox_SearchDirectoriesBypassPatterns.Lines); System.Collections.Generic.List <System.Text.RegularExpressions.Regex> regexList = new System.Collections.Generic.List <System.Text.RegularExpressions.Regex>(); foreach (string bypassPattern in parameters.SearchDirectoriesBypassPatterns) { regexList.Add(new System.Text.RegularExpressions.Regex(bypassPattern)); } parameters.BypassRegexes = regexList.ToArray(); if (richTextBox_SourcePaths.Text.EndsWith(getCollectPhotoDataExtension())) { parameters.LogFilePath_ThreadResult = richTextBox_SourcePaths.Lines[richTextBox_SourcePaths.Lines.Length - 1]; } else { parameters.SourcePaths = richTextBox_SourcePaths.Lines; } parameters.DestinationRootDirectory = richTextBox_DestinationRootDirectory.Text; parameters.DestinationSubDirectories = stripBlankLines(richTextBox_DestinationSubDirectories.Lines); parameters.FileNameComponent = stripBlankLines(richTextBox_FileNameComponent.Lines); parameters.Command = richTextBox_Command.Text; parameters.CommandOptions = richTextBox_CommandOptions.Text; parameters.SearchDirectoryDeepnessLimitation = getSearchDirectoryDeepnessLimitation(); parameters.AutoStart = checkBox_AutoStart.Checked; parameters.AutoDetermine = checkBox_AutoDetermine.Checked; parameters.FilterWhileSearching = checkBox_FilterWhileSearching.Checked; parameters.CopyLowGradeImage = checkBox_CopyLowGradeImage.Checked; parameters.DeleteAfterCopy = checkBox_DeleteAfterCopy.Checked; parameters.DeleteSourceIfDestinationAlreadyExists = checkBox_DeleteAlreadyExists.Checked; parameters.DeleteReadOnly = checkBox_DeleteReadOnly.Checked; parameters.AutoRename = checkBox_AutoRename.Checked; parameters.MultipleJobs = checkBox_MultipleJobs.Checked; parameters.CreateSubDestinationRootDirectory = checkBox_CreateSubDestinationRootDirectory.Checked; try { FileWriterWithAppendMode logger = FileWriterWithAppendMode.Open(buildCollectPhotoLogFilePath(richTextBox_DestinationRootDirectory.Text, CultureStrings.TextTaskParameters)); string configContent = GetConfigContent(parameters); logger.Write(configContent); logger.Close(); } catch (System.Exception ex) { logException(ex); } return(parameters); }
private ThreadParameters copyFiles(ThreadParameters parameters) { System.Collections.Generic.List <string> sourcePaths = new System.Collections.Generic.List <string>(); if (parameters.SourcePaths != null) { sourcePaths.AddRange(parameters.SourcePaths); } FileWriterWithAppendMode sourcePathLogger = null; FileWriterWithAppendMode deletedSourcePathLogger = null; FileWriterWithAppendMode destinationPathLogger = null; lock (copyFilesJobs) { sourcePathLogger = FileWriterWithAppendMode.Open(buildCollectPhotoLogFilePath(parameters.DestinationRootDirectory, CultureStrings.LogFileCopiedSourcePaths)); } lock (copyFilesJobs) { destinationPathLogger = FileWriterWithAppendMode.Open(buildCollectPhotoLogFilePath(parameters.DestinationRootDirectory, CultureStrings.LogFileCopiedDestinationPaths)); } lock (copyFilesJobs) { deletedSourcePathLogger = FileWriterWithAppendMode.Open(buildCollectPhotoLogFilePath(parameters.DestinationRootDirectory, CultureStrings.LogFileToBeDeletedSourcePaths)); } ThreadProgress threadProgress = new ThreadProgress(); resetThreadProgress(ref threadProgress, sourcePaths.Count, sourcePathLogger.FilePath, deletedSourcePathLogger.FilePath, destinationPathLogger.FilePath); if (parameters.LogFilePath_ThreadResult == null) { threadProgress.ProgressBarStyle = System.Windows.Forms.ProgressBarStyle.Marquee; backgroundWorker_Copy.ReportProgress(0, threadProgress); parameters = filterSourcePaths(searchDirectories(parameters)); } if (System.IO.File.Exists(parameters.LogFilePath_ThreadResult)) { sourcePaths.AddRange(System.IO.File.ReadAllLines(parameters.LogFilePath_ThreadResult, System.Text.Encoding.Unicode).ToList()); } threadProgress.CountTotal = sourcePaths.Count; threadProgress.ProgressBarStyle = System.Windows.Forms.ProgressBarStyle.Blocks; for (int i = 0; i < sourcePaths.Count; i++) { string sourcePath = sourcePaths[i]; string destinationPath = null; threadProgress.SourcePath = sourcePath; bool isCopy = false; bool isOverwriteCopy = false; bool alreadyExists = false; try { if (isMatchingFilePath(sourcePath, parameters.IncludeFileExtensions) || isMatchingFilePath(sourcePath, parameters.IncludeFileExtensionAndFileNameMap)) { destinationPath = buildImageDestinationFilePath(parameters, sourcePath, null); preCopyFile(parameters, sourcePath, ref destinationPath, ref alreadyExists, ref isCopy); } else if (isMatchingFilePath(sourcePath, parameters.ExcludeFileExtensions) || isMatchingFilePath(sourcePath, parameters.IncludeFileExtensionAndFileNameMap.Keys.ToArray())) { } else if (isImageFile(sourcePath)) { bool isLowGradeImage = false; using (System.Drawing.Image image = getImage(sourcePath)) { isLowGradeImage = !isImageLargerThanMinDimension(parameters.FileNameComponent, image); destinationPath = buildImageDestinationFilePath(parameters, sourcePath, image); } if (parameters.CopyLowGradeImage && (isLowGradeImage || destinationPath == null)) { destinationPath = buildUniqueDestinationFilePath(parameters, sourcePath); preCopyFile(parameters, sourcePath, ref destinationPath, ref alreadyExists, ref isCopy); } else if (destinationPath != null) { preCopyFile(parameters, sourcePath, ref destinationPath, ref alreadyExists, ref isCopy); if (!alreadyExists && isCopy && System.IO.File.Exists(destinationPath) && getFileSize(destinationPath) < getFileSize(sourcePath)) { isOverwriteCopy = true; } } } if (parameters.DeleteSourceIfDestinationAlreadyExists && alreadyExists && areTwoCopies(sourcePath, destinationPath)) { deletedSourcePathLogger.WriteLine(sourcePath); deletedSourcePathLogger.WriteLine(destinationPath); DeleteFileAndRelatedDirectoriesWithoutException(sourcePath, parameters); reportSkippedCopy(ref threadProgress, destinationPath, i); } else if (isCopy) { if (isOverwriteCopy) { overwriteFile(sourcePath, destinationPath); } else if (parameters.DeleteAfterCopy) { createDirectoryForFile(destinationPath); System.IO.File.Move(sourcePath, destinationPath); DeleteFileAndRelatedDirectoriesWithoutException(sourcePath, parameters); } else { copyFile(sourcePath, destinationPath); } sourcePathLogger.WriteLine(sourcePath); destinationPathLogger.WriteLine(destinationPath); reportSuccessCopy(ref threadProgress, destinationPath, i); } else { reportSkippedCopy(ref threadProgress, destinationPath, i); } } catch (System.Exception ex) { logException(ex); reportSkippedCopy(ref threadProgress, destinationPath, i); } sourcePathLogger.Flush(); destinationPathLogger.Flush(); deletedSourcePathLogger.Flush(); } sourcePathLogger.Close(); destinationPathLogger.Close(); deletedSourcePathLogger.Close(); FileWriterWithAppendMode.GlobalWrite(threadProgress.ToString()); return(parameters); }
private ThreadParameters executeCommands(ThreadParameters parameters) { System.Collections.Generic.List <string> sourcePaths = new System.Collections.Generic.List <string>(); if (parameters.SourcePaths != null) { sourcePaths.AddRange(parameters.SourcePaths); } if (parameters.LogFilePath_ThreadResult != null && System.IO.File.Exists(parameters.LogFilePath_ThreadResult)) { sourcePaths.AddRange(System.IO.File.ReadAllLines(parameters.LogFilePath_ThreadResult, System.Text.Encoding.Unicode)); } else if (parameters.SourceDirectories != null && parameters.SourceDirectories.Length > 0) { parameters = filterSourcePaths(searchDirectories(parameters)); sourcePaths.AddRange(System.IO.File.ReadAllLines(parameters.LogFilePath_ThreadResult, System.Text.Encoding.Unicode)); } lock (copyFilesJobs) { parameters.LogFilePath_ThreadResult = buildCollectPhotoDataFilePath(parameters.DestinationRootDirectory, CultureStrings.LogFileExecuteCommandsResult); } FileWriterWithAppendMode logger = FileWriterWithAppendMode.Open(parameters.LogFilePath_ThreadResult); string sourcePathTemplate = fillCommandParameter(fillCommandParameter(parameters.CommandOptions, CommandParameterKey_Command, parameters.Command, 0), CommandParameterKey_DestinationRootDirectory, parameters.DestinationRootDirectory, 0); string commandName = System.IO.Path.GetFileNameWithoutExtension(parameters.Command); if (sourcePathTemplate.IndexOf(commandName, System.StringComparison.InvariantCultureIgnoreCase) == -1) { sourcePathTemplate = doubleQuoteText(parameters.Command) + " " + sourcePathTemplate; } for (int i = 0; i < sourcePaths.Count; i++) { string command = fillCommandParameter(sourcePathTemplate, CommandParameterKey_SourcePath, sourcePaths[i], 0); command = fillCommandParameter(fillCommandParameter(command, fileSizeId, getFileSize(sourcePaths[i]).ToString(), 0), originalFileNameId, getCollectPhotoOriginalFileName(sourcePaths[i]), 0); if (backgroundWorker_ExecuteCommands.CancellationPending) { return(parameters); } else { logger.WriteLine(command); if (backgroundWorker_ExecuteCommands.IsBusy) { backgroundWorker_ExecuteCommands.ReportProgress(calculatePercentage(sourcePaths.Count, i), command); } try { System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(command); info.CreateNoWindow = true; info.UseShellExecute = false; info.RedirectStandardOutput = true; info.RedirectStandardError = true; System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = info; process.Start(); string stdout = process.StandardOutput.ReadToEnd(); string stderr = process.StandardError.ReadToEnd(); backgroundWorker_ExecuteCommands.ReportProgress(calculatePercentage(sourcePaths.Count, i), stdout); backgroundWorker_ExecuteCommands.ReportProgress(calculatePercentage(sourcePaths.Count, i), stderr); logger.WriteLine(stdout); logger.WriteLine(stderr); } catch (System.Exception ex) { logException(ex); } } } logger.Close(); return(parameters); }