public static bool MatchPattern(string pattern, string path) { List <string> matches = new List <string>(); Regex regex = FindFilesPatternToRegex.Convert(pattern); return(regex.IsMatch(path)); }
private void CreateFilenameRegex() { _compiledFileSpecRegex = null; RegexOptions options = FileSpecMatchCase ? RegexOptions.Compiled : RegexOptions.Compiled | RegexOptions.IgnoreCase; if (FileSpecRegex) { options |= FileSpecRegexOptions; try { _compiledFileSpecRegex = new Regex(FileSpec, options); } catch (Exception ex) { Trace.WriteLine(String.Format("Invalid regex pattern '{0}' - {1}", FileSpecRegex, ex.Message)); } } else { try { _compiledFileSpecRegex = FindFilesPatternToRegex.Convert(FileSpec, options); } catch (Exception ex) { Trace.WriteLine(String.Format("Invalid wildcard pattern '{0}' - {1}", FileSpecRegex, ex.Message)); } } }
public static bool FilenameVerification(string filename, string mask) { List <string> matches = new List <string>(); Regex regex = FindFilesPatternToRegex.Convert(mask); bool result = regex.IsMatch(filename); return(result); }
//static void Main(string[] args) //{ // string[] names = { "hello.t", "HelLo.tx", "HeLLo.txt", "HeLLo.txtsjfhs", "HeLLo.tx.sdj", "hAlLo20984.txt" }; // string[] matches; // matches = FindFilesEmulator("hello.tx", names); // matches = FindFilesEmulator("H*o*.???", names); // matches = FindFilesEmulator("hello.txt", names); // matches = FindFilesEmulator("lskfjd30", names); //} /// <summary> /// Returns files that match the pattern. /// </summary> /// <param name="pattern">Pattern to which files have to match.</param> /// <param name="names">File names to check against the pattern.</param> /// <returns>An array of files names that match the pattern.</returns> public static string[] FindFiles(string pattern, string[] names) { var regex = FindFilesPatternToRegex.Convert(pattern); if (pattern.Length < 1000) { return(names.Where(name => regex.IsMatch(name)).ToArray()); } return(names.AsParallel().Where(name => regex.IsMatch(name)).ToArray()); }
public string[] FindFilesEmulator(string pattern, string[] names) { List <string> matches = new List <string>(); Regex regex = FindFilesPatternToRegex.Convert(pattern); foreach (string s in names) { if (regex.IsMatch(s)) { matches.Add(s); } } return(matches.ToArray()); }
public static IEnumerable <string> MatchFiles(IEnumerable <string> patterns, IEnumerable <string> names, bool exclude) { List <string> matches = new List <string>(); Regex nameRegex = null; bool match = false; // bool noPatterns = true; foreach (string path in names) { string cleanPath = path.Replace("/", "\\"); string fileNameOnly = FileNamePart(path); foreach (string pattern in patterns) { //noPatterns = false; string cleanPattern = pattern.Replace("/", "\\"); string namePattern = FileNamePart(cleanPattern); string pathPattern = PathPart(cleanPattern); if (namePattern != String.Empty) { nameRegex = FindFilesPatternToRegex.Convert(namePattern); } match = (pathPattern == String.Empty ? true : MatchPathOnly(cleanPattern, cleanPath)) && (namePattern == String.Empty ? true : nameRegex.IsMatch(fileNameOnly)); if (match) { break; } } if (match != exclude) { yield return(path); } } // think this was from when we had the patterns/paths loops inverted. Should never be needed (actually causes dups now) // .. if the pattern loop is skipped, match will be false, as is correct. //if (noPatterns) //{ // foreach (string name in names) // { // yield return name; // } //} }
/// <summary> /// Returns true or false based on whether the passed filename /// should be excluded from the results /// </summary> /// <param name="filename"></param> /// <param name="excludePatterns"></param> /// <returns></returns> public static bool FileInExcludeList(string filename, string[] excludePatterns) { List <string> matches = new List <string>(); bool retval = false; foreach (string pattern in excludePatterns) { Regex regex = FindFilesPatternToRegex.Convert(pattern); if (regex.IsMatch(filename)) { retval = true; break; } } return(retval); }
public IEnumerable <PackageResult> list_run(ChocolateyConfiguration config) { this.Log().Info(() => ""); string match = config.Input; if (String.IsNullOrEmpty(match)) { match = "*"; } var reMatcher = FindFilesPatternToRegex.Convert(match); foreach (var key in get_apps()) { if (!reMatcher.IsMatch(key.DisplayName)) { continue; } var r = new PackageResult(key.DisplayName, key.DisplayName, key.InstallLocation); NuGet.SemanticVersion version; if (!NuGet.SemanticVersion.TryParse(key.DisplayVersion, out version)) { version = new NuGet.SemanticVersion(1, 0, 0, 0); } var rp = new NuGet.RegistryPackage() { Id = key.DisplayName, Version = version }; r.Package = rp; rp.IsPinned = key.IsPinned; rp.RegistryKey = key; yield return(r); } }
public override bool ReadDirectoryEntry(object fileNode, object fileDesc, string pattern, string marker, ref object context, out string fileName, out FileInfo fileInfo) { if (fileDesc is FileMetadata metadata) { if (!(context is EnumerateDirectoryContext currentContext)) { Logger.LogTrace( $"{nameof ( ReadDirectoryEntry )} of \"{metadata . Name}\"."); if (null != pattern) { pattern = pattern.Replace('<', '*'). Replace('>', '?'). Replace('"', '.'); } else { pattern = "*"; } Regex fileNamePatternRegex = FindFilesPatternToRegex.Convert(pattern); string pathPrefix; if (metadata.Name.EndsWith("\\")) { pathPrefix = metadata.Name; } else { pathPrefix = $"{metadata . Name}\\"; } string escapedPathPrefix = Regex.Escape(pathPrefix); Regex pathPrefixRegex = new Regex( @$ "^{escapedPathPrefix}([^\\]+)$", RegexOptions.Compiled); IEnumerable <FileMetadata> fileInFolder; lock ( DataContext ) { fileInFolder = DataContext. FileMetadata. Where((fileMetadata) => !fileMetadata.IsDeleted). Where( fileMetadata => fileMetadata. Name.StartsWith(pathPrefix)). OrderBy(fileMetadata => fileMetadata.Name). AsEnumerable( ); } List <(string FileName, FileMetadata FileMetadata)> availableFiles = fileInFolder.Select( fileMetadata => { Match pathPrefixMatch = pathPrefixRegex.Match( fileMetadata. Name); if (pathPrefixMatch.Success) { string matchedFileName = pathPrefixMatch. Groups [1]. Value; Match fileNameMatch = fileNamePatternRegex.Match( matchedFileName); if (fileNameMatch.Success) { return(FileName: matchedFileName, FileMetadata: fileMetadata); } } return(default);
/// <summary> /// Evaluates registry keys and updates the snapshop with items /// </summary> /// <param name="key">The key.</param> /// <param name="snapshot">The snapshot.</param> public void evaluate_keys(RegistryKeyInfo regkey, RegistryKey key, Registry snapshot, string packageId = null, string version = null, bool?nugetInstallable = null) { if (key == null) { return; } FaultTolerance.try_catch_with_logging_exception( () => { Regex reMatchFile = null; if (packageId != null) { reMatchFile = FindFilesPatternToRegex.Convert(packageId); } foreach (var subKeyName in key.GetSubKeyNames()) { if (reMatchFile != null && !reMatchFile.IsMatch(subKeyName)) { continue; } regkey.SubKeyName = subKeyName; FaultTolerance.try_catch_with_logging_exception( () => evaluate_keys(regkey, key.OpenSubKey(subKeyName, RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey), snapshot, packageId, version, nugetInstallable), "Failed to open subkey named '{0}' for '{1}', likely due to permissions".format_with(subKeyName, key.Name), logWarningInsteadOfError: true); } }, "Failed to open subkeys for '{0}', likely due to permissions".format_with(key.Name), logWarningInsteadOfError: true); var appKey = new RegistryApplicationKey { Hive = regkey.hive, KeyPath = key.Name, RegistryView = key.View, DefaultValue = key.get_value_as_string(""), DisplayName = key.get_value_as_string("DisplayName") }; if (string.IsNullOrWhiteSpace(appKey.DisplayName)) { appKey.DisplayName = appKey.DefaultValue; } bool addRegEntry = false; if (!string.IsNullOrWhiteSpace(appKey.DisplayName)) { addRegEntry = true; appKey.PackageId = key.get_value_as_string("PackageId"); if (string.IsNullOrWhiteSpace(appKey.PackageId)) { appKey.PackageId = regkey.SubKeyName; } string s = key.get_value_as_string(nameof(RegistryApplicationKey.IsPinned)); if (string.IsNullOrWhiteSpace(s)) { appKey.IsPinned = false; } else { appKey.IsPinned = s != "0"; } appKey.InstallLocation = key.get_value_as_string("InstallLocation"); if (nugetInstallable.HasValue) { string dir = appKey.InstallLocation; bool isNugetInstallable = false; if (!String.IsNullOrEmpty(dir)) { string parentDir = System.IO.Path.GetDirectoryName(dir); string parentDirName = System.IO.Path.GetFileName(dir); if (parentDirName == appKey.PackageId) { string nuspecPath = System.IO.Path.Combine(dir, appKey.PackageId + NuGet.Constants.ManifestExtension); isNugetInstallable = System.IO.File.Exists(nuspecPath); } } if (nugetInstallable.Value != isNugetInstallable) { addRegEntry = false; } } } if (addRegEntry) { appKey.UninstallString = key.get_value_as_string("UninstallString"); if (!string.IsNullOrWhiteSpace(key.get_value_as_string("QuietUninstallString"))) { appKey.UninstallString = key.get_value_as_string("QuietUninstallString"); appKey.HasQuietUninstall = true; } // informational appKey.Publisher = key.get_value_as_string("Publisher"); appKey.InstallDate = key.get_value_as_string("InstallDate"); appKey.InstallSource = key.get_value_as_string("InstallSource"); appKey.Language = key.get_value_as_string("Language"); // Version appKey.DisplayVersion = key.get_value_as_string("DisplayVersion"); appKey.Version = key.get_value_as_string("Version"); appKey.VersionMajor = key.get_value_as_string("VersionMajor"); appKey.VersionMinor = key.get_value_as_string("VersionMinor"); // installinformation appKey.SystemComponent = key.get_value_as_string("SystemComponent") == "1"; appKey.WindowsInstaller = key.get_value_as_string("WindowsInstaller") == "1"; appKey.NoRemove = key.get_value_as_string("NoRemove") == "1"; appKey.NoModify = key.get_value_as_string("NoModify") == "1"; appKey.NoRepair = key.get_value_as_string("NoRepair") == "1"; appKey.ReleaseType = key.get_value_as_string("ReleaseType"); appKey.ParentKeyName = key.get_value_as_string("ParentKeyName"); appKey.DisplayIcon = key.get_value_as_string("DisplayIcon"); long size = 0; if (long.TryParse(key.get_value_as_string("EstimatedSize"), out size)) { appKey.EstimatedSize = size; } if (appKey.WindowsInstaller || appKey.UninstallString.to_string().to_lower().Contains("msiexec")) { appKey.InstallerType = InstallerType.Msi; } if (key.Name.EndsWith("_is1") || !string.IsNullOrWhiteSpace(key.get_value_as_string("Inno Setup: Setup Version"))) { appKey.InstallerType = InstallerType.InnoSetup; } if (!string.IsNullOrWhiteSpace(key.get_value_as_string("dwVersionMajor"))) { appKey.InstallerType = InstallerType.Nsis; appKey.VersionMajor = key.get_value_as_string("dwVersionMajor"); appKey.VersionMinor = key.get_value_as_string("dwVersionMinor"); appKey.VersionRevision = key.get_value_as_string("dwVersionRev"); appKey.VersionBuild = key.get_value_as_string("dwVersionBuild"); } if (appKey.ReleaseType.is_equal_to("Hotfix") || appKey.ReleaseType.is_equal_to("Update Rollup") || appKey.ReleaseType.is_equal_to("Security Update") || appKey.DefaultValue.to_string().StartsWith("KB", ignoreCase: true, culture: CultureInfo.InvariantCulture)) { appKey.InstallerType = InstallerType.HotfixOrSecurityUpdate; } if (appKey.ReleaseType.is_equal_to("ServicePack")) { appKey.InstallerType = InstallerType.ServicePack; } // assume NSIS if we still don't know and we find uninst.exe if (appKey.InstallerType == InstallerType.Unknown && appKey.UninstallString.to_string().to_lower().Contains("uninst.exe")) { appKey.InstallerType = InstallerType.Nsis; } if (appKey.InstallerType == InstallerType.Unknown && appKey.HasQuietUninstall) { appKey.InstallerType = InstallerType.Custom; } if (appKey.InstallerType == InstallerType.Msi) { get_msi_information(appKey, key); } if (_logOutput) { //if (appKey.is_in_programs_and_features() && appKey.InstallerType == InstallerType.Unknown) //{ foreach (var name in key.GetValueNames()) { //var kind = key.GetValueKind(name); var value = key.get_value_as_string(name); if (name.is_equal_to("QuietUninstallString") || name.is_equal_to("UninstallString")) { Console.WriteLine("key - {0}|{1}={2}|Type detected={3}|install location={4}".format_with(key.Name, name, value.to_string(), appKey.InstallerType.to_string(), appKey.InstallLocation.to_string())); } //Console.WriteLine("key - {0}, name - {1}, kind - {2}, value - {3}".format_with(key.Name, name, kind, value.to_string())); } //} } snapshot.RegistryKeys.Add(appKey); } key.Close(); key.Dispose(); }
public Variable(XmlNode config) { this.config = config; try { type = config.Attributes["type"].Value; } catch (Exception) { Console.WriteLine("Variable defined without a \"type\" attribute"); ConfigOK = false; return; } variableLookup = SetVar("variableLookup", false); if (variableLookup) { lookupSource = SetVar("lookupSource", null); } dataFile = SetVar("dataFile", null); token = SetVar("token", null); externalName = SetVar("externalName", null); field = SetVar("field", null); excelLookupSheet = SetVar("excelLookupSheet", null); excelKeyColumn = SetVar("excelKeyColumn", null); excelValueColumn = SetVar("excelValueColumn", null); csvKeyField = SetVar("csvKeyField", -1); csvValueField = SetVar("csvValueField", -1); if (type == "intRange") { try { lowerLimit = int.Parse(config.Attributes["lowerLimit"].Value); } catch (Exception) { if (config.Attributes["lowerLimit"] != null && config.Attributes["lowerLimit"].Value.StartsWith("@@")) { varSubstitionRequired = true; subDict.Add("lowerLimit", config.Attributes["lowerLimit"].Value); } else { lowerLimit = 0; } } digits = SetVar("digits", -1); try { upperLimit = int.Parse(config.Attributes["upperLimit"].Value); } catch (Exception) { if (config.Attributes["upperLimit"] != null && config.Attributes["upperLimit"].Value.StartsWith("@@")) { varSubstitionRequired = true; subDict.Add("upperLimit", config.Attributes["upperLimit"].Value); } else { upperLimit = 0; } } } if (type == "intgaussian") { try { normalInt = int.Parse(config.Attributes["normalInt"].Value); } catch (Exception) { if (config.Attributes["normalInt"] != null && config.Attributes["normalInt"].Value.StartsWith("@@")) { varSubstitionRequired = true; subDict.Add("normalInt", config.Attributes["normalInt"].Value); } else { normalInt = 0; } } stdDev = SetVar("stdDev", 1.0); digits = SetVar("digits", -1); } if (type == "doublegaussian") { try { normalDouble = double.Parse(config.Attributes["normalDouble"].Value); } catch (Exception) { if (config.Attributes["normalDouble"] != null && config.Attributes["normalDouble"].Value.StartsWith("@@")) { varSubstitionRequired = true; subDict.Add("normalDouble", config.Attributes["normalDouble"].Value); } else { normalDouble = 0.0; } } stdDev = SetVar("stdDev", 1.0); } if (token == null && externalName == null) { ErrorMsg = "Variable defined without a token or externalName value defined"; ConfigOK = false; return; } try { if (config.ParentNode.Attributes["stopOnDataEnd"] != null) { abortOnListEnd = bool.Parse(config.ParentNode.Attributes["stopOnDataEnd"].Value); } else { abortOnListEnd = false; } } catch (Exception) { abortOnListEnd = false; } if (type == "flightInfo") { xpath = SetVar("xpath", null); sub = SetVar("sub", null); } if (type == "sequence") { seqNum = SetVar("seed", 1); digits = SetVar("digits", -1); } if (type == "datetime") { lowerOffset = SetVar("lowerOffset", 0); upperOffset = SetVar("upperOffset", 0); format = SetVar("format", "yyyy-MM-ddTHH:mm:ss.fffK"); dtRelative = SetVar("relative", false); delta = SetVar("delta", 0); } if (type == "timestamp") { format = SetVar("format", "yyyy-MM-ddTHH:mm:ss.fffK"); } if (type == "fixed") { fixedValue = SetVar("fixedValue", ""); } if (type == "value" || type == "valueSequence") { XElement xElem = XElement.Load(config.CreateNavigator().ReadSubtree()); IEnumerable <XElement> valueDefn = from value in xElem.Descendants("value") select value; foreach (XElement v in valueDefn) { values.Add(v.Value); } listLength = values.Count; } if (type == "file") { try { srcDir = config.Attributes["srcDir"]?.Value; if (srcDir == null) { Console.WriteLine("File type defined without a \"srcDir\" attribute"); return; } } catch (Exception) { Console.WriteLine("File type defined without a \"srcDir\" attribute"); return; } if (!Directory.Exists(srcDir)) { Console.WriteLine($"Source Directory {srcDir} not valid "); return; } string fileFilter = "*.*"; try { fileFilter = config.Attributes["fileFilter"].Value; } catch (Exception) { fileFilter = "*.*"; } Regex regex = FindFilesPatternToRegex.Convert(fileFilter); foreach (string file in Directory.GetFiles(srcDir)) { if (File.Exists(file)) { if (regex.IsMatch(file)) { fileEntries.Add(file); } } } listLength = fileEntries.Count; } if (type == "csvfield") { field = SetVar("field", null); } if (type == "excelCol") { field = SetVar("excelCol", null); } if (type == "xmlElement") { field = SetVar("xmlXPath", null); } if (type == "jsonElement") { field = SetVar("field", null); } if (type == "dbField") { field = SetVar("field", null); } ConfigOK = true; }
public virtual IEnumerable <string> GetFiles(string path, string filter) { Regex matcher = FindFilesPatternToRegex.Convert(filter); return(GetFiles(path).Where(f => matcher.IsMatch(Path.GetFileName(f)))); }