Reputation: 6555
I have a method that allows the user to specify a remote directory and a searchPattern with with to search files in the remote directory. Since I use third party libraries when retrieving the names of the files from the remote location, I am unable to take advantage of System.IO's Directory.GetFiles() routine which allows me specify the searchPattern when getting the files.
Basic String.Compare does not properly match the filename against the supplied pattern. Anyone know a more effective way of doing the matching please?
public IList<String> GetMatchingRemoteFiles(String SearchPattern, bool ignoreCase)
{
IList<String> matchingFileNames = new List<String>();
var RemoteFiles = thirdPartyTool.ftpClient.GetCurrentDirectoryContents();
foreach( String filename in RemoteFiles)
if( String.Compare(filename, SearchPattern, ignoreCase) == 0)
matchingFileNames.Add(filename);
return matchingFileNames;
}
Thanks in advance.
Upvotes: 2
Views: 6913
Reputation: 13716
File matching with wildcards (*
, ?
) is called "glob" matching or "globbing". You can try converting the user-entered glob search to a regular expression, then using that. There's an example here:
Regex.Escape( wildcardExpression ).Replace( @"\*", ".*" ).Replace( @"\?", "." );
This would then get passed into a RegEx.Match()
as the pattern, where you currently have String.Compare()
Upvotes: 6
Reputation: 149088
If you can specify what kinds of search strings this method will accept, you can use regular expressions. Here's an example which also uses Linq for brevity:
public IList<String> GetMatchingRemoteFiles(String SearchPattern, bool ignoreCase)
{
var options = ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;
return thirdPartyTool.ftpClient.GetCurrentDirectoryContents()
.Where(fn => Regex.Matches(fn, SearchPattern, options))
.ToList();
}
Even if you cannot control what kinds of search strings this method accepts, it's still probably easier to convert the search string to a regular expression than write your own algorithm for matching the patterns. See Bobson's answer for details on how to do this.
Upvotes: 2