如何按文件创建/修改时间降序排列目录文件并绑定到GridView展示
问题根源
你之前使用OrderByDescending不生效的核心原因如下:
- 你代码中拆分出来的
FileDate是字符串类型,直接对字符串做降序排序走的是字符字典序,不会按照日期的时间先后逻辑排序 - 依赖文件名拆分日期的方式容错率极低,只要文件名格式不符合规则就会出现排序错误,更推荐直接读取文件系统存储的创建/修改时间
修复方案
方案1:基于文件名日期排序(适合必须依赖文件名中日期的场景)
先将文件名拆分的日期字符串转为DateTime类型后再做降序排序,代码修改如下:
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Results/")); List<Thing> lst = new List<Thing>(); foreach (string filePath in filePaths) { string filename = Path.GetFileNameWithoutExtension(filePath); string dateStr = filename.Split('_')[0]; // 转换为日期类型用于排序 if(DateTime.TryParse(dateStr, out DateTime sortDate)) { lst.Add(new Thing() { FileDate = dateStr, FileName = filename.Split('_')[1], FilePath = filePath, // 建议在Thing类中新增DateTime类型的SortDate字段存储排序用的时间 SortDate = sortDate }); } } // 排序后再绑定到GridView GridView1.DataSource = lst.OrderByDescending(t => t.SortDate).ToList(); GridView1.DataBind();
方案2:基于文件实际修改/创建时间排序(更稳定可靠)
直接读取文件属性的时间来排序,不依赖文件名格式,代码如下:
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Results/")); List<Thing> lst = new List<Thing>(); foreach (string filePath in filePaths) { FileInfo fi = new FileInfo(filePath); string filename = Path.GetFileNameWithoutExtension(filePath); lst.Add(new Thing() { // 可根据需求换成fi.CreationTime取文件创建时间 FileDate = fi.LastWriteTime.ToString("yyyy-MM-dd"), FileName = filename.Split('_')[1], FilePath = filePath, SortDate = fi.LastWriteTime }); } GridView1.DataSource = lst.OrderByDescending(t => t.SortDate).ToList(); GridView1.DataBind();
内容的提问来源于stack exchange,提问作者Web Funda
相关产品推荐
相关产品推荐

