C# DirectoryInfo.GetFiles().Where()用法

.Net技术 码拜 8年前 (2016-05-31) 3020次浏览
现在要实现将某一目录下全部图片格式的文件过滤出来,有*.tif,*.jpg,*.bmp等,GetFiles(“*.tif || *.jpg”)这样写又不对,本人在网上查用where,但是还是不行,麻烦高手帮看一下吧
解决方案

10

string CommonImgPath = "";
List<string> extensions = new List<string>() { ".tif", ".jpg", ".bmp" };
var files = Directory.GetFiles(CommonImgPath);
foreach (var file in files)
{
    string ext = Path.GetExtension(file);
    if (extensions.Contains(ext))
        Console.WriteLine(file);
}

4

 string directory = @"E:\pic";
            string[] files = Directory.GetFiles(directory).Where(x => x.EndsWith(".tif") || x.EndsWith(".jpg" title="C# DirectoryInfo.GetFiles().Where()用法")).ToArray();

6

.Where(s => s.EndsWith(“.tif”) || s.EndsWith(“.jpg”));
应写作
.Where(s => s.Extension == “.tif” || s.Extension == “.jpg”);

3

引用:

.Where(s => s.EndsWith(“.tif”) || s.EndsWith(“.jpg”));
应写作
.Where(s => s.Extension == “.tif” || s.Extension == “.jpg”);

这个正解!Extension 是扩展名  文件操作类有个方法GETExtensions 获取扩展名

3

引用:
 string directory = @"E:\pic";
            string[] files = Directory.GetFiles(directory).Where(x => x.EndsWith(".tif") || x.EndsWith(".jpg" title="C# DirectoryInfo.GetFiles().Where()用法")).ToArray();

经验证,这种方法可行

4

引用:
Quote: 引用:
Quote: 引用:

.Where(s => s.EndsWith(“.tif”) || s.EndsWith(“.jpg”));
应写作
.Where(s => s.Extension == “.tif” || s.Extension == “.jpg”);

这个正解!Extension 是扩展名  文件操作类有个方法GETExtensions 获取扩展名

问一下这个s是什么啊,不需要怎么获取吗

不需要

10

好说,加个ToLower

string CommonImgPath = "";
List<string> extensions = new List<string>() { ".tif", ".jpg", ".bmp" };
var files = Directory.GetFiles(CommonImgPath);
foreach (var file in files)
{
    string ext = Path.GetExtension(file);
    if (extensions.Contains(ext.ToLower()))
        Console.WriteLine(file);
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C# DirectoryInfo.GetFiles().Where()用法
喜欢 (0)
[1034331897@qq.com]
分享 (0)