How to determine if a File Matches a File Mask?

后端 未结 13 1691
清歌不尽
清歌不尽 2020-12-14 07:14

I need to decide whether file name fits to file mask. The file mask could contain * or ? characters. Is there any simple solution for this?

bool bFits = Fits         


        
13条回答
  •  无人及你
    2020-12-14 07:25

    How about using reflection to get access to the function in the .NET framework?

    Like this:

    public class PatternMatcher
    {
      public delegate bool StrictMatchPatternDelegate(string expression, string name);
      public StrictMatchPatternDelegate StrictMatchPattern;
      public PatternMatcher()
      {
        Type patternMatcherType = typeof(FileSystemWatcher).Assembly.GetType("System.IO.PatternMatcher");
        MethodInfo patternMatchMethod = patternMatcherType.GetMethod("StrictMatchPattern", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
        StrictMatchPattern = (expression, name) => (bool)patternMatchMethod.Invoke(null, new object[] { expression, name });
      }
    }
    
    void Main()
    {
      PatternMatcher patternMatcher = new PatternMatcher();
      Console.WriteLine(patternMatcher.StrictMatchPattern("*.txt", "test.txt")); //displays true
      Console.WriteLine(patternMatcher.StrictMatchPattern("*.doc", "test.txt")); //displays false
    }
    

提交回复
热议问题