Mam dla Ciebie pełną odpowiedź w 95%, np. FindFiles(string)
.
5%, którego nie ma, jest zachowanie krótkich nazw/długich nazw w drugiej notatce w dokumentacji MSDN dla tej funkcji.
Jeśli nadal chcesz uzyskać takie zachowanie, musisz wykonać obliczenie krótkiej nazwy każdego łańcucha, który masz w tablicy wejściowej, a następnie dodać długą nazwę do kolekcji dopasowań, jeśli długa lub krótka nazwa pasuje do wzorca.
Oto kod:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace FindFilesRegEx
{
class Program
{
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);
}
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();
}
internal static class FindFilesPatternToRegex
{
private static Regex HasQuestionMarkRegEx = new Regex(@"\?", RegexOptions.Compiled);
private static Regex IllegalCharactersRegex = new Regex("[" + @"\/:<>|" + "\"]", RegexOptions.Compiled);
private static Regex CatchExtentionRegex = new Regex(@"^\s*.+\.([^\.]+)\s*$", RegexOptions.Compiled);
private static string NonDotCharacters = @"[^.]*";
public static Regex Convert(string pattern)
{
if (pattern == null)
{
throw new ArgumentNullException();
}
pattern = pattern.Trim();
if (pattern.Length == 0)
{
throw new ArgumentException("Pattern is empty.");
}
if(IllegalCharactersRegex.IsMatch(pattern))
{
throw new ArgumentException("Pattern contains illegal characters.");
}
bool hasExtension = CatchExtentionRegex.IsMatch(pattern);
bool matchExact = false;
if (HasQuestionMarkRegEx.IsMatch(pattern))
{
matchExact = true;
}
else if(hasExtension)
{
matchExact = CatchExtentionRegex.Match(pattern).Groups[1].Length != 3;
}
string regexString = Regex.Escape(pattern);
regexString = "^" + Regex.Replace(regexString, @"\\\*", ".*");
regexString = Regex.Replace(regexString, @"\\\?", ".");
if(!matchExact && hasExtension)
{
regexString += NonDotCharacters;
}
regexString += "$";
Regex regex = new Regex(regexString, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return regex;
}
}
}
}
Dla każdego, kto napotkał to pytanie teraz, gdy minęło wiele lat, znalazłem na forum społecznościowym MSDN, że metoda GetFiles() zaakceptuje * i? znaki wieloznaczne w parametrze searchPattern. (Przynajmniej w .NET 3.5, 4.0 i 4.5) Directory.GetFiles (ścieżki ciąg, ciąg searchPattern) http://msdn.microsoft.com/en-us/library/wz42302f.aspx – jgerman