C#:获取指定目录中符合条件的文件名集合

/* ----------------------------------------------------------
文件名称:Folder.cs

作者:秦建辉

MSN:splashcn@msn.com
QQ:36748897

博客:http://www.firstsolver.com/wordpress/

开发环境:
    Visual Studio V2010
    .NET Framework 4 Client Profile

版本历史:
    V1.0    2012年04月16日
            获取指定目录中符合条件的文件名集合
------------------------------------------------------------ */
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace Splash.IO
{
    public static class Folder
    {
        /// <summary>
        /// 返回指定目录中与指定的搜索模式匹配的文件的名称(包含它们的路径),并使用一个值以确定是否搜索子目录
        /// </summary>
        /// <param name="folderPath">将从其检索文件的目录</param>
        /// <param name="filter">搜索模式匹配</param>
        /// <param name="searchOption">指定搜索操作应包括所有子目录还是仅包括当前目录</param>
        /// <returns>包含指定目录中与指定搜索模式匹配的文件的名称列表</returns>
        /// <remarks>
        /// 搜索模式示例:
        ///     图像文件:String filter = "\\.(bmp|gif|jpg|jpe|png|tiff|tif)$";
        ///     扩展名为“.dat”的文件:String filter = "\\.dat$";
        /// </remarks>
        public static String[] GetFiles(String folderPath, String filter, SearchOption searchOption)
        {   // 获取文件列表
            String[] FileEntries = Directory.GetFiles(folderPath, "*", searchOption);
            if (FileEntries.Length == 0)
                return null;
            else if (String.IsNullOrEmpty(filter))
                return FileEntries;

            // 建立正则表达式
            Regex rx = new Regex(filter, RegexOptions.IgnoreCase);

            // 过滤文件
            List<String> FilterFileEntries = new List<String>(FileEntries.Length);
            foreach (String FileName in FileEntries)
            {
                if (rx.IsMatch(FileName))
                {
                    FilterFileEntries.Add(FileName);
                }
            }

            return (FilterFileEntries.Count == 0) ? null : FilterFileEntries.ToArray();
        }
    }
}

Comments are closed.