排序目录.GetFiles()

发布于 2024-07-05 03:02:12 字数 363 浏览 8 评论 0原文

System.IO.Directory.GetFiles() 返回一个string[]。 返回值的默认排序顺序是什么? 我是按名字假设的,但如果是的话,当前的文化对其影响有多大? 您可以将其更改为创建日期之类的内容吗?

更新: MSDN 指出 .Net 3.5 不保证排序顺序,但该页面的 2.0 版本根本没有说明任何内容,并且两个页面都不会帮助您按创建或创建等内容进行排序。修改时间。 一旦您拥有数组(它仅包含字符串),该信息就会丢失。 我可以构建一个比较器来检查它获取的每个文件,但这意味着在 .GetFiles() 方法可能已经执行此操作时重复访问文件系统。 看起来效率很低。

System.IO.Directory.GetFiles() returns a string[]. What is the default sort order for the returned values? I'm assuming by name, but if so how much does the current culture effect it? Can you change it to something like creation date?

Update: MSDN points out that the sort order is not guaranteed for .Net 3.5, but the 2.0 version of the page doesn't say anything at all and neither page will help you sort by things like creation or modification time. That information is lost once you have the array (it contains only strings). I could build a comparer that would check for each file it gets, but that means accessing the file system repeatedly when presumably the .GetFiles() method already does this. Seems very inefficient.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

染墨丶若流云 2024-07-12 03:02:13

更简洁的 VB.Net 版本,如果有人感兴趣的话

Dim filePaths As Linq.IOrderedEnumerable(Of IO.FileInfo) = _
  New DirectoryInfo("c:\temp").GetFiles() _
   .OrderBy(Function(f As FileInfo) f.CreationTime)
For Each fi As IO.FileInfo In filePaths
  ' Do whatever you wish here
Next

A more succinct VB.Net version, if anyone is interested

Dim filePaths As Linq.IOrderedEnumerable(Of IO.FileInfo) = _
  New DirectoryInfo("c:\temp").GetFiles() _
   .OrderBy(Function(f As FileInfo) f.CreationTime)
For Each fi As IO.FileInfo In filePaths
  ' Do whatever you wish here
Next
始终不够爱げ你 2024-07-12 03:02:13

您可以实现自定义 iComparer 来进行排序。 读取文件的文件信息并根据需要进行比较。

IComparer comparer = new YourCustomComparer();
Array.Sort(System.IO.Directory.GetFiles(), comparer);

msdn 信息 IComparer 界面

You can implement custom iComparer to do sorting. Read the file info for files and compare as you like.

IComparer comparer = new YourCustomComparer();
Array.Sort(System.IO.Directory.GetFiles(), comparer);

msdn info IComparer interface

微暖i 2024-07-12 03:02:13

更简洁的 VB.Net 版本...非常好。 谢谢。
要以相反的顺序遍历列表,请添加reverse方法...

For Each fi As IO.FileInfo In filePaths.reverse
  ' Do whatever you wish here
Next

A more succinct VB.Net version...is very nice. Thank you.
To traverse the list in reverse order, add the reverse method...

For Each fi As IO.FileInfo In filePaths.reverse
  ' Do whatever you wish here
Next
春夜浅 2024-07-12 03:02:13

MSDN 文档 声明不保证任何订单返回值。 您必须使用 Sort() 方法。

The MSDN Documentation states that there is no guarantee of any order on the return values. You have to use the Sort() method.

海之角 2024-07-12 03:02:13

您可以编写自定义 IComparer 接口来按创建日期排序,然后将其传递给 Array.Sort。 您可能还想查看 StrCmpLogical,它用于执行 Explorer 使用的排序(将数字与文本正确排序)。

You could write a custom IComparer interface to sort by creation date, and then pass it to Array.Sort. You probably also want to look at StrCmpLogical, which is what is used to do the sorting Explorer uses (sorting numbers correctly with text).

七秒鱼° 2024-07-12 03:02:13

如果您想按创建日期之类的内容进行排序,您可能需要使用 DirectoryInfo.GetFiles,然后使用合适的谓词对结果数组进行排序。

If you want to sort by something like creation date you probably need to use DirectoryInfo.GetFiles and then sort the resulting array using a suitable Predicate.

白色秋天 2024-07-12 03:02:13

只是一个想法。 我喜欢找到一种简单的方法并尝试重新使用现有的资源。 如果我要对文件进行排序,我只需创建一个进程并将 syscal 设置为“DIR [x:\Folders\SubFolders*.*] /s /b /on”并捕获输出。

使用系统的 DIR 命令,您可以按以下方式排序:

/O          List by files in sorted order.
sortorder    N  By name (alphabetic)       S  By size (smallest first)
             E  By extension (alphabetic)  D  By date/time (oldest first)
             G  Group directories first    -  Prefix to reverse order

The /S switch includes sub folders

我不确定 D = 按日期/时间是否使用 LastModifiedDate 或 FileCreateDate。 但是如果所需的排序顺序已经内置在 DIR 命令中,我将通过调用 syscall 来获取它。 而且速度很快。 我只是个懒人;)

经过一番谷歌搜索后,我发现切换到按特定日期/时间排序:-

/t [[:]TimeField] : Specifies which time field to display or use for sorting. The following list describes each of the values you can use for TimeField. 

Value Description 
c : Creation
a : Last access
w : Last written

Just an idea. I like to find an easy way out and try re use already available resources. if I were to sort files I would've just create a process and make syscal to "DIR [x:\Folders\SubFolders*.*] /s /b /on" and capture the output.

With system's DIR command you can sort by :

/O          List by files in sorted order.
sortorder    N  By name (alphabetic)       S  By size (smallest first)
             E  By extension (alphabetic)  D  By date/time (oldest first)
             G  Group directories first    -  Prefix to reverse order

The /S switch includes sub folders

I AM NOT SURE IF D = By Date/Time is using LastModifiedDate or FileCreateDate. But if the needed sort order is already built-in in the DIR command, I will get that by calling syscall. And it's FAST. I am just the lazy guy ;)

After a little googling I found switch to sort by particular date/time:-

/t [[:]TimeField] : Specifies which time field to display or use for sorting. The following list describes each of the values you can use for TimeField. 

Value Description 
c : Creation
a : Last access
w : Last written
隔纱相望 2024-07-12 03:02:12

如果您对文件的属性(例如 CreationTime)感兴趣,那么使用 System.IO.DirectoryInfo.GetFileSystemInfos() 会更有意义。
然后,您可以使用 System.Linq 中的扩展方法之一对它们进行排序,例如:

DirectoryInfo di = new DirectoryInfo("C:\\");
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.OrderBy(f => f.CreationTime);

编辑 - 抱歉,我没有注意到 .NET2.0 标记,因此忽略 LINQ 排序。 不过,使用 System.IO.DirectoryInfo.GetFileSystemInfos() 的建议仍然有效。

If you're interested in properties of the files such as CreationTime, then it would make more sense to use System.IO.DirectoryInfo.GetFileSystemInfos().
You can then sort these using one of the extension methods in System.Linq, e.g.:

DirectoryInfo di = new DirectoryInfo("C:\\");
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.OrderBy(f => f.CreationTime);

Edit - sorry, I didn't notice the .NET2.0 tag so ignore the LINQ sorting. The suggestion to use System.IO.DirectoryInfo.GetFileSystemInfos() still holds though.

你在看孤独的风景 2024-07-12 03:02:12

在 .NET 2.0 中,您需要使用 Array.Sort 对 FileSystemInfos 进行排序。

此外,您可以使用 Comparer 委托来避免仅为比较而声明一个类:

DirectoryInfo dir = new DirectoryInfo(path);
FileSystemInfo[] files = dir.GetFileSystemInfos();

// sort them by creation time
Array.Sort<FileSystemInfo>(files, delegate(FileSystemInfo a, FileSystemInfo b)
                                    {
                                        return a.LastWriteTime.CompareTo(b.LastWriteTime);
                                    });

In .NET 2.0, you'll need to use Array.Sort to sort the FileSystemInfos.

Additionally, you can use a Comparer delegate to avoid having to declare a class just for the comparison:

DirectoryInfo dir = new DirectoryInfo(path);
FileSystemInfo[] files = dir.GetFileSystemInfos();

// sort them by creation time
Array.Sort<FileSystemInfo>(files, delegate(FileSystemInfo a, FileSystemInfo b)
                                    {
                                        return a.LastWriteTime.CompareTo(b.LastWriteTime);
                                    });
风筝在阴天搁浅。 2024-07-12 03:02:12

这是我使用过的 VB.Net 解决方案。

首先创建一个类来比较日期:

Private Class DateComparer
    Implements System.Collections.IComparer

    Public Function Compare(ByVal info1 As Object, ByVal info2 As Object) As Integer Implements System.Collections.IComparer.Compare
        Dim FileInfo1 As System.IO.FileInfo = DirectCast(info1, System.IO.FileInfo)
        Dim FileInfo2 As System.IO.FileInfo = DirectCast(info2, System.IO.FileInfo)

        Dim Date1 As DateTime = FileInfo1.CreationTime
        Dim Date2 As DateTime = FileInfo2.CreationTime

        If Date1 > Date2 Then Return 1
        If Date1 < Date2 Then Return -1
        Return 0
    End Function
End Class

然后在对数组进行排序时使用比较器:

Dim DirectoryInfo As New System.IO.DirectoryInfo("C:\")
Dim Files() As System.IO.FileInfo = DirectoryInfo.GetFiles()
Dim comparer As IComparer = New DateComparer()
Array.Sort(Files, comparer)

Here's the VB.Net solution that I've used.

First make a class to compare dates:

Private Class DateComparer
    Implements System.Collections.IComparer

    Public Function Compare(ByVal info1 As Object, ByVal info2 As Object) As Integer Implements System.Collections.IComparer.Compare
        Dim FileInfo1 As System.IO.FileInfo = DirectCast(info1, System.IO.FileInfo)
        Dim FileInfo2 As System.IO.FileInfo = DirectCast(info2, System.IO.FileInfo)

        Dim Date1 As DateTime = FileInfo1.CreationTime
        Dim Date2 As DateTime = FileInfo2.CreationTime

        If Date1 > Date2 Then Return 1
        If Date1 < Date2 Then Return -1
        Return 0
    End Function
End Class

Then use the comparer while sorting the array:

Dim DirectoryInfo As New System.IO.DirectoryInfo("C:\")
Dim Files() As System.IO.FileInfo = DirectoryInfo.GetFiles()
Dim comparer As IComparer = New DateComparer()
Array.Sort(Files, comparer)
跨年 2024-07-12 03:02:12
Dim Files() As String
Files = System.IO.Directory.GetFiles("C:\")
Array.Sort(Files)
Dim Files() As String
Files = System.IO.Directory.GetFiles("C:\")
Array.Sort(Files)
隔岸观火 2024-07-12 03:02:12

来自 msdn

不保证返回文件名的顺序; 如果需要特定的排序顺序,请使用 Sort() 方法。

Sort() 方法是标准 Array.Sort (),它接受 IComparables(以及其他重载),因此如果您按创建日期排序,它将根据计算机设置处理本地化。

From msdn:

The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required.

The Sort() method is the standard Array.Sort(), which takes in IComparables (among other overloads), so if you sort by creation date, it will handle localization based on the machine settings.

微凉徒眸意 2024-07-12 03:02:12

你是对的,默认是我的名字asc。 我发现更改排序顺序的唯一方法是从 FileInfo 集合创建数据表。

然后,您可以使用数据表中的 DefaultView 并使用 .Sort 方法对目录进行排序。

这是相当复杂且相当缓慢的,但我希望有人会发布更好的解决方案。

You are correct, the default is my name asc. The only way I have found to change the sort order it to create a datatable from the FileInfo collection.

You can then used the DefaultView from the datatable and sort the directory with the .Sort method.

This is quite involve and fairly slow but I'm hoping someone will post a better solution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文