图片查看器:如何在添加至ListBox前过滤非图片文件并按写入时间排序
解决图片文件过滤问题
快速实现:基于扩展名过滤
先定义常见图片格式的扩展名集合,做不区分大小写的匹配,再结合LINQ简化过滤和排序逻辑,替换你原来的代码即可:
// 定义需要保留的图片扩展名,不区分大小写 var imageExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp" }; var dirInfo = new DirectoryInfo(currentDir); // 过滤图片文件 + 按最后写入时间降序排序 var sortedImageFiles = dirInfo.GetFiles() .Where(file => imageExtensions.Contains(file.Extension)) .OrderByDescending(file => file.LastWriteTime); // 添加到ListBox foreach (var file in sortedImageFiles) { listBoxImages.Items.Add(file.Name); }
为什么替换冒泡排序?
你原来的嵌套循环是手动实现冒泡排序,用OrderByDescending不仅代码更简洁,内部采用的排序算法(快速排序/稳定排序)性能也比冒泡排序高,可读性更强。
进阶方案:基于文件头判断(防扩展名篡改)
如果担心文件扩展名被恶意修改,可通过读取文件头来判断是否为真实图片,准确性更高:
// 判断文件是否为真实图片的辅助方法 private bool IsGenuineImage(FileInfo file) { try { using (var stream = file.OpenRead()) { var headerBytes = new byte[4]; stream.Read(headerBytes, 0, headerBytes.Length); // 匹配常见图片的文件头特征 return (headerBytes[0] == 0xFF && headerBytes[1] == 0xD8 && headerBytes[2] == 0xFF) // JPG || (headerBytes[0] == 0x89 && headerBytes[1] == 0x50 && headerBytes[2] == 0x4E && headerBytes[3] == 0x47) // PNG || (headerBytes[0] == 0x47 && headerBytes[1] == 0x49 && headerBytes[2] == 0x46 && headerBytes[3] == 0x38); // GIF } } catch { // 读取失败时默认判定为非图片 return false; } }
使用时只需把过滤条件替换成:
.Where(file => IsGenuineImage(file))
内容的提问来源于stack exchange,提问作者user19945067
相关产品推荐
相关产品推荐

