Absolute Path with Wild Card Filtering

I have a list of strings containing files that should be ignored to manipulate goals. Therefore, I am curious how to handle a situation in which there is a wild card.

For example, possible entries in my list of strings:

C:\Windows\System32\bootres.dll C:\Windows\System32\*.dll 

The first example, which, it seems to me, is easy to handle, I can just do a line check (ignoring the case) to see if the file matches. However, I'm not sure how to determine if a given file can match the wild card expression in the list.

The little background is what I do. The user can copy the file to / from the location, however, if the file matches any file in my list of lines, I do not want to allow copying.

There may be a need for a more effective approach to solving this issue.

The files that I want to exclude are read from the configuration file, and I get the string value of the path that I am trying to copy. It seems that I have all the information I need to complete the task, this is just a matter of the best approach.

+4
source share
2 answers
 IEnumerable<string> userFiles = Directory.EnumerateFiles(path, userFilter); // a combination of any files from any source, eg: IEnumerable<string> yourFiles = Directory.EnumerateFiles(path, yourFilter); // or new string[] { path1, path2, etc. }; IEnumerable<string> result = userFiles.Except(yourFiles); 

To parse a comma delimited string:

 string input = @"c:\path1\*.dll;d:\path2\file.ext"; var result = input.Split(";") //.Select(path => path.Trim()) .Select(path => new { Path = Path.GetFullPath(path), // c:\path1 Filter = Path.GetFileName(path) // *.dll }) .SelectMany(x => Directory.EnumerateFiles(x.Path, x.Filter)); 
+2
source

You can use Directory.GetFiles() and use the path file name to see if there is a corresponding file:

 string[] filters = ... return filters.Any(f => Directory.GetFiles(Path.GetDirectoryName(f), Path.GetFileName(f)).Length > 0); 

Update:
I really was wrong. You have a set of file filters containing wildcards, and you want to check the user's input on them. You can use the solution provided by @hometoast in the comments :

 // Configured filter: string[] fileFilters = new [] { @"C:\Windows\System32\bootres.dll", @":\Windows\System32\*.dll" } // Construct corresponding regular expression. Note Regex.Escape! RegexOptions options = RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase; Regex[] patterns = fileFilters .Select(f => new Regex("^" + Regex.Escape(f).Replace("\\*", ".*") + "$", options)) .ToArray(); // Match against user input: string userInput = @"c:\foo\bar\boo.far"; if (patterns.Any(p => p.IsMatch(userInput))) { // user input matches one of configured filters } 
+1
source

Source: https://habr.com/ru/post/1416426/


All Articles