private static void EnrichWithMissingFiles(BestMatchInfo bestMatchInfo, string outputDirPath) { var a = bestMatchInfo.MatchingFiles.First(); // NOTE: there are at least 2 files in the list (see previous note) for (var i = 1; i < bestMatchInfo.MatchingFiles.Count; i++) { var b = bestMatchInfo.MatchingFiles[i]; var nbMissingNumbers = b.Number - a.Number - 1; var missingNum = a.Number; while ((nbMissingNumbers--) > 0) { missingNum++; var missingNumStr = bestMatchInfo.RefNumberSeemsPadded ? missingNum.ToPaddedString(bestMatchInfo.RefNumberStr.Length) : missingNum.ToString(); var missingFileName = bestMatchInfo.Prefix + missingNumStr + bestMatchInfo.Suffix; var missingFilePath = Path.Combine(outputDirPath, missingFileName); var missingMatchingFile = new MatchingFile(new FileInfo(missingFilePath), missingNumStr, missingNum); bestMatchInfo.MatchingFiles.Insert(i++, missingMatchingFile); } a = b; } }
/// <summary> /// Try to guess the list of files to join according to the given file example /// </summary> /// <param name="exampleFile"></param> /// <param name="inputFiles"></param> /// <param name="outputFile"></param> /// <param name="guessMissingFiles"></param> /// <returns></returns> public static bool TryGuessFilesToJoin(string exampleFile, out string[] inputFiles, out string outputFile, bool guessMissingFiles = true) { var exampleFileInfo = new FileInfo(exampleFile); var exampleFileDirectory = exampleFileInfo.Directory; if (exampleFileDirectory == null || !exampleFileDirectory.Exists) { inputFiles = new string[0]; outputFile = ""; return(false); } var allFiles = exampleFileDirectory.GetFiles(); var regex = new Regex("\\d+"); var exampleFileName = exampleFileInfo.Name; BestMatchInfo?bestMatchInfo = null; foreach (Match numberMatch in regex.Matches(exampleFileName)) { var prefixTmp = exampleFileName.Substring(0, numberMatch.Index); var suffixTmp = exampleFileName.Substring(numberMatch.Index + numberMatch.Length); var refNumber = numberMatch.Value; var matchingFiles = ListMatchingFiles(prefixTmp, refNumber, suffixTmp, allFiles, out var refNumberSeemsPadded); if (matchingFiles.Count < 2) // NOTE: At least 2 files needed (the current matching file + another) { continue; } if (bestMatchInfo == null || matchingFiles.Count > bestMatchInfo.MatchingFiles.Count) { bestMatchInfo = new BestMatchInfo(matchingFiles, prefixTmp, suffixTmp, refNumber, refNumberSeemsPadded); } } if (bestMatchInfo == null) { inputFiles = new string[0]; outputFile = ""; return(false); } if (guessMissingFiles) { EnrichWithMissingFiles(bestMatchInfo, exampleFileDirectory.FullName); } inputFiles = bestMatchInfo.MatchingFiles.Select(m => m.FileInfo.FullName).ToArray(); outputFile = Path.Combine(exampleFileDirectory.FullName, BuildOutputFileName(bestMatchInfo.Prefix, bestMatchInfo.Suffix, exampleFileDirectory.FullName)); return(true); }