searchPattern通配符获取文件夹下多种格式的图片

先介绍一下searchPattern通配符

通配符 描述
* 零个或多个字符
? 正好一个字符

 

举例:
    ①“*t”搜索 path 中所有以字母“t”结尾的名称
    ②“s*”搜索 path 中所有以字母“s”开头的名称

通配符的行为与其长度有一定的关系,扩展名恰好是三个字符时的 searchPattern 匹配行为与扩展名多于三个字符时不同

恰好为三个字符的 searchPattern 返回扩展名为三个或三个以上字符的文件。

“*.abc”返回扩展名为 .abc、.abcd、.abcde、.abcdef 等的文件。 

一个字符、两个字符或三个以上字符的 searchPattern 只返回扩展名恰好等于该长度的文件。

“*.rmvb”只返回扩展名为 .rmvb的文件。 

“*.Cache”只返回扩展名为 .Cache的文件。 

“*.csproj”只返回扩展名为 .csproj 的文件。

 

 

这是做一个小工具时写的一个方法,
主要功能是获取一个文件夹下多种格式的图片。

当然,用于获取别的文件也是可以的。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
private string[] GetImages(string dirPath, params string[] searchPatterns)
{
    if (searchPatterns.Length <= 0)
    {
        return null;
    }
    else
    {
        DirectoryInfo di = new DirectoryInfo(dirPath);
        FileInfo[][] fis = new FileInfo[searchPatterns.Length][];
        int count = 0;
        for (int i = 0; i < searchPatterns.Length; i++)
        {
            FileInfo[] fileInfos = di.GetFiles(searchPatterns[i]);
            fis[i] = fileInfos;
            count += fileInfos.Length;
        }
        string[] files = new string[count];
        int n = 0;
        for (int i = 0; i <= fis.GetUpperBound(0); i++)
        {
            for (int j = 0; j < fis[i].Length; j++)
            {
                string temp = fis[i][j].FullName;
                files[n] = temp;
                n++;
            }
        }
        return files;
    }
}

 

  调用

1
string[] files = GetPictures("*.gif", "*.jpg", "*.png");
posted @   liqipeng  阅读(1507)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示