How do I check if a filename matches a wildcard pattern

前端 未结 8 1571
青春惊慌失措
青春惊慌失措 2020-11-30 06:16

I\'ve got a wildcard pattern, perhaps \"*.txt\" or \"POS??.dat\".

I also have list of filenames in memory that I need to compare to that pattern.

How would

8条回答
  •  庸人自扰
    2020-11-30 07:10

    Just call the Windows API function PathMatchSpecExW().

    [Flags]
    public enum MatchPatternFlags : uint
    {
        Normal          = 0x00000000,   // PMSF_NORMAL
        Multiple        = 0x00000001,   // PMSF_MULTIPLE
        DontStripSpaces = 0x00010000    // PMSF_DONT_STRIP_SPACES
    }
    
    class FileName
    {
        [DllImport("Shlwapi.dll", SetLastError = false)]
        static extern int PathMatchSpecExW([MarshalAs(UnmanagedType.LPWStr)] string file,
                                           [MarshalAs(UnmanagedType.LPWStr)] string spec,
                                           MatchPatternFlags flags);
    
        /*******************************************************************************
        * Function:     MatchPattern
        *
        * Description:  Matches a file name against one or more file name patterns.
        *
        * Arguments:    file - File name to check
        *               spec - Name pattern(s) to search foe
        *               flags - Flags to modify search condition (MatchPatternFlags)
        *
        * Return value: Returns true if name matches the pattern.
        *******************************************************************************/
    
        public static bool MatchPattern(string file, string spec, MatchPatternFlags flags)
        {
            if (String.IsNullOrEmpty(file))
                return false;
    
            if (String.IsNullOrEmpty(spec))
                return true;
    
            int result = PathMatchSpecExW(file, spec, flags);
    
            return (result == 0);
        }
    }
    

提交回复
热议问题