首页 > 解决方案 > ListBox 按文件创建时间排序

问题描述

我的 listBox1 充满了 txt 文件的名称。它按字母顺序自动对它们进行排序。但我需要按创建时间对这些文件进行排序,从最新到最旧。有人能帮我吗?

标签: c#

解决方案


你没有给我们太多的继续:P

但我会尽我最大的努力来帮助你。因为我不知道您是如何填充列表的(手动或使用代码),所以我无法真正指导您。

但是,假设您是通过代码完成的。我输入的以下代码段可能会帮助您找到所需的内容

//array of file names (these need to be paths to files, so if you do not prefix it with ./path/ or anything, then the executable needs to be in the same folder)
//If you are debugging, make sure the paths are correct if you expect them to be in the same folder, it should then be in the debug folder.
//If you included some test files in the solution and want them copied to your debug folder. Click on them, go to the properties pane, and set build action to content, and one of the other properties should read copy of newer instead of never copy
var fileNames = new string[]{"1.txt", "2.txt", "3.txt"};

var fileInfos = fileNames.Select(f => new FileInfo(f));

var orderedFileInfos = fileInfos.OrderBy(f => f.CreationTime);

orderedFileInfos 现在是一个 FileInfo 类型的列表,按创建时间升序排列。

这是你可以用来填充你的 ListBox

我希望我能帮助你在你的项目中取得进展。


推荐阅读