C# Directory.GetFiles()获取多个类型格式的文件

var files = Directory.GetFiles("C:\\path", "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg"));

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

先介绍一下searchPattern通配符

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

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

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

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

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

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

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

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

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

这是做一个小项目时写的一个方法,

主要功能是获取一个文件夹下多种格式的图片。

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

    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;  
        }  
    }  

调用

    string[] files = GetPictures("*.gif", "*.jpg", "*.png");  
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值