Example #1
0
        // ReSharper restore StringLiteralTypo
        public void CompactPath(string pathToCompact, int maxLength, string expectedResult)
        {
            var shortPath = FileTools.CompactPathString(pathToCompact, maxLength);

            Console.WriteLine(shortPath);

            Assert.AreEqual(expectedResult, shortPath, "Unexpected short path for {0}: {1}", pathToCompact, shortPath);
        }
Example #2
0
 /// <summary>
 /// Shorten pathToCompact to a maximum length of maxLength
 /// Examples:
 /// C:\...\B..\Finance..
 /// C:\...\W..\Business\Finances.doc
 /// C:\My Doc..\Word\Business\Finances.doc
 /// </summary>
 /// <param name="pathToCompact"></param>
 /// <param name="maxLength">Maximum length of the shortened path</param>
 /// <returns>Shortened path</returns>
 // ReSharper disable once UnusedMember.Global
 public static string CompactPathString(string pathToCompact, int maxLength = 40)
 {
     return(FileTools.CompactPathString(pathToCompact, maxLength));
 }
Example #3
0
        private bool RecurseDirectoriesWork(
            string inputDirectoryPath,
            string directoryNameMatchPattern,
            string parameterFilePath,
            string outputDirectoryAlternatePath,
            int recursionLevel,
            int maxLevelsToRecurse)
        {
            // If maxLevelsToRecurse is <=0, we recurse infinitely

            DirectoryInfo inputDirectory;

            string outputDirectoryPathToUse;

            try
            {
                inputDirectory = new DirectoryInfo(inputDirectoryPath);
            }
            catch (Exception ex)
            {
                // Input directory path error
                HandleException("Error in RecurseDirectoriesWork", ex);
                ErrorCode = ProcessDirectoriesErrorCodes.InvalidInputDirectoryPath;
                return(false);
            }

            try
            {
                if (!string.IsNullOrWhiteSpace(outputDirectoryAlternatePath))
                {
                    outputDirectoryAlternatePath = Path.Combine(outputDirectoryAlternatePath, inputDirectory.Name);
                    outputDirectoryPathToUse     = string.Copy(outputDirectoryAlternatePath);
                }
                else
                {
                    outputDirectoryPathToUse = string.Empty;
                }
            }
            catch (Exception ex)
            {
                // Output file path error
                HandleException("Error in RecurseDirectoriesWork", ex);
                ErrorCode = ProcessDirectoriesErrorCodes.InvalidOutputDirectoryPath;
                return(false);
            }

            try
            {
                OnDebugEvent("Examining " + inputDirectoryPath);
                bool success;

                if (recursionLevel == 1 && directoryNameMatchPattern == "*")
                {
                    // Need to process the current directory
                    success = ProcessDirectory(inputDirectory.FullName, outputDirectoryPathToUse, parameterFilePath, true);
                    if (success)
                    {
                        DirectoriesProcessed += 1;
                    }
                    else
                    {
                        DirectoryProcessErrors += 1;
                    }
                }

                // Process any matching subdirectory in this directory

                var matchCount   = 0;
                var lastProgress = DateTime.UtcNow;

                var directoriesToProcess = inputDirectory.GetDirectories(directoryNameMatchPattern).ToList();

                foreach (var directory in directoriesToProcess)
                {
                    matchCount++;

                    // This is the % complete in this directory only; not overall
                    var percentComplete = matchCount / (float)directoriesToProcess.Count * 100;
                    OnProgressUpdate("Process " + directory.FullName, percentComplete);

                    if (outputDirectoryPathToUse.Length > 0)
                    {
                        var alternateOutputDirectoryPath = Path.Combine(outputDirectoryPathToUse, directory.Name);
                        success = ProcessDirectory(directory.FullName, alternateOutputDirectoryPath, parameterFilePath, true);
                    }
                    else
                    {
                        success = ProcessDirectory(directory.FullName, string.Empty, parameterFilePath, true);
                    }

                    if (success)
                    {
                        DirectoriesProcessed += 1;
                    }
                    else
                    {
                        DirectoryProcessErrors += 1;
                    }

                    if (AbortProcessing)
                    {
                        break;
                    }

                    if (!(DateTime.UtcNow.Subtract(lastProgress).TotalSeconds >= 1))
                    {
                        continue;
                    }

                    lastProgress = DateTime.UtcNow;
                    OnStatusEvent(string.Format("{0:F1}% complete in {1}", percentComplete, FileTools.CompactPathString(inputDirectoryPath)));
                }
            }
            catch (Exception ex)
            {
                HandleException("Error in RecurseDirectoriesWork", ex);
                ErrorCode = ProcessDirectoriesErrorCodes.InvalidInputDirectoryPath;
                return(false);
            }

            if (AbortProcessing)
            {
                return(false);
            }

            // If maxLevelsToRecurse is <=0, we recurse infinitely
            // otherwise, compare recursionLevel to maxLevelsToRecurse
            if (maxLevelsToRecurse > 0 && recursionLevel > maxLevelsToRecurse)
            {
                return(true);
            }

            // Call this function for each of the subdirectories of inputDirectory
            foreach (var subdirectory in inputDirectory.GetDirectories())
            {
                var success = RecurseDirectoriesWork(subdirectory.FullName, directoryNameMatchPattern,
                                                     parameterFilePath, outputDirectoryAlternatePath,
                                                     recursionLevel + 1, maxLevelsToRecurse);
                if (!success)
                {
                    return(false);
                }
            }

            return(true);
        }
        private bool RecurseDirectoriesWork(
            string inputDirectoryPath,
            string fileNameMatch,
            string outputDirectoryName,
            string parameterFilePath,
            string outputDirectoryAlternatePath,
            bool recreateDirectoryHierarchyInAlternatePath,
            IList <string> extensionsToParse,
            int recursionLevel,
            int maxLevelsToRecurse)
        {
            // If maxLevelsToRecurse is <=0, process all subdirectories

            DirectoryInfo inputDirectory;

            var processAllExtensions = false;

            string outputDirectoryPathToUse;

            try
            {
                inputDirectory = new DirectoryInfo(inputDirectoryPath);
            }
            catch (Exception ex)
            {
                // Input directory path error
                HandleException("Error in RecurseDirectoriesWork examining inputDirectoryPath", ex);
                ErrorCode = ProcessFilesErrorCodes.InvalidInputFilePath;
                return(false);
            }

            try
            {
                if (!string.IsNullOrWhiteSpace(outputDirectoryAlternatePath))
                {
                    if (recreateDirectoryHierarchyInAlternatePath)
                    {
                        outputDirectoryAlternatePath = Path.Combine(outputDirectoryAlternatePath, inputDirectory.Name);
                    }

                    outputDirectoryPathToUse = Path.Combine(outputDirectoryAlternatePath, outputDirectoryName);
                }
                else
                {
                    outputDirectoryPathToUse = outputDirectoryName;
                }
            }
            catch (Exception ex)
            {
                // Output file path error
                HandleException("Error in RecurseDirectoriesWork validating the alternate output directory path", ex);
                ErrorCode = ProcessFilesErrorCodes.InvalidOutputDirectoryPath;
                return(false);
            }

            try
            {
                // Validate extensionsToParse()
                for (var extensionIndex = 0; extensionIndex <= extensionsToParse.Count - 1; extensionIndex++)
                {
                    if (extensionsToParse[extensionIndex] == null)
                    {
                        extensionsToParse[extensionIndex] = string.Empty;
                    }
                    else
                    {
                        if (!extensionsToParse[extensionIndex].StartsWith("."))
                        {
                            extensionsToParse[extensionIndex] = "." + extensionsToParse[extensionIndex];
                        }

                        if (extensionsToParse[extensionIndex] == ".*")
                        {
                            processAllExtensions = true;
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Error in RecurseDirectoriesWork validating the extensions to parse", ex);
                ErrorCode = ProcessFilesErrorCodes.UnspecifiedError;
                return(false);
            }

            var filesToProcess = new List <FileInfo>();

            try
            {
                if (!string.IsNullOrWhiteSpace(outputDirectoryPathToUse))
                {
                    // Update the cached output directory path
                    mOutputDirectoryPath = string.Copy(outputDirectoryPathToUse);
                }

                OnDebugEvent("Examining " + inputDirectoryPath);

                // Find matching files in this directory
                foreach (var inputFile in inputDirectory.GetFiles(fileNameMatch))
                {
                    for (var extensionIndex = 0; extensionIndex <= extensionsToParse.Count - 1; extensionIndex++)
                    {
                        if (processAllExtensions ||
                            string.Equals(inputFile.Extension, extensionsToParse[extensionIndex], StringComparison.OrdinalIgnoreCase))
                        {
                            filesToProcess.Add(inputFile);
                        }
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                OnWarningEvent("Access denied to " + inputDirectoryPath);
                return(true);
            }
            catch (Exception ex)
            {
                //if (ex.Message.StartsWith("Access", StringComparison.OrdinalIgnoreCase) &&
                //    ex.Message.EndsWith("Denied.", StringComparison.OrdinalIgnoreCase))
                //{
                //    OnWarningEvent("Access denied to " + inputDirectoryPath);
                //    return true;
                //}

                HandleException("Error in RecurseDirectoriesWork while finding files to process", ex);
                ErrorCode = ProcessFilesErrorCodes.InvalidInputFilePath;
                return(false);
            }

            try
            {
                var matchCount   = 0;
                var lastProgress = DateTime.UtcNow;

                // Process the files that were found
                foreach (var inputFile in filesToProcess)
                {
                    matchCount++;

                    // This is the % complete in this directory only; not overall
                    var percentComplete = matchCount / (float)filesToProcess.Count * 100;
                    OnProgressUpdate("Process " + inputFile.FullName, percentComplete);

                    var success = ProcessFile(inputFile.FullName, outputDirectoryPathToUse, parameterFilePath, true);

                    if (success)
                    {
                        FilesProcessed++;
                    }
                    else
                    {
                        FileProcessErrors++;
                    }

                    if (AbortProcessing)
                    {
                        break;
                    }

                    if (!(DateTime.UtcNow.Subtract(lastProgress).TotalSeconds >= 1))
                    {
                        continue;
                    }

                    lastProgress = DateTime.UtcNow;
                    OnStatusEvent(string.Format("{0:F1}% complete in {1}", percentComplete, FileTools.CompactPathString(inputDirectoryPath)));
                }
            }
            catch (Exception ex)
            {
                HandleException("Error in RecurseDirectoriesWork while processing files", ex);
                ErrorCode = ProcessFilesErrorCodes.InvalidInputFilePath;
                return(false);
            }

            if (AbortProcessing)
            {
                return(false);
            }

            // If maxLevelsToRecurse is <=0, we recurse infinitely
            // otherwise, compare recursionLevel to maxLevelsToRecurse
            if (maxLevelsToRecurse > 0 && recursionLevel > maxLevelsToRecurse)
            {
                return(true);
            }

            // Call this function for each of the subdirectories of inputDirectory
            foreach (var subdirectory in inputDirectory.GetDirectories())
            {
                var success = RecurseDirectoriesWork(subdirectory.FullName, fileNameMatch, outputDirectoryName,
                                                     parameterFilePath, outputDirectoryAlternatePath,
                                                     recreateDirectoryHierarchyInAlternatePath, extensionsToParse,
                                                     recursionLevel + 1, maxLevelsToRecurse);

                if (!success)
                {
                    return(false);
                }
            }

            return(true);
        }