How to determine if a File Matches a File Mask?

后端 未结 13 1692
清歌不尽
清歌不尽 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:49

    I didn't want to copy the source code and like @frankhommers I came up with a reflection based solution.

    Notice the code comment about the use of wildcards in the name argument I found in the reference source.

        public static class PatternMatcher
        {
            static MethodInfo strictMatchPatternMethod;
            static PatternMatcher()
            {
                var typeName = "System.IO.PatternMatcher";
                var methodName = "StrictMatchPattern";
                var assembly = typeof(Uri).Assembly;
                var type = assembly.GetType(typeName, true);
                strictMatchPatternMethod = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public) ?? throw new MissingMethodException($"{typeName}.{methodName} not found");
            }
    
            /// 
            /// Tells whether a given name matches the expression given with a strict (i.e. UNIX like) semantics.
            /// 
            /// Supplies the input expression to check against
            /// Supplies the input name to check for.
            /// 
            public static bool StrictMatchPattern(string expression, string name)
            {
                // https://referencesource.microsoft.com/#system/services/io/system/io/PatternMatcher.cs
                // If this class is ever exposed for generic use,
                // we need to make sure that name doesn't contain wildcards. Currently 
                // the only component that calls this method is FileSystemWatcher and
                // it will never pass a name that contains a wildcard.
                if (name.Contains('*')) throw new FormatException("Wildcard not allowed");
                return (bool)strictMatchPatternMethod.Invoke(null, new object[] { expression, name });
            }
        }
    

提交回复
热议问题