VB.net框架4.8:如何按创建日期对文件夹中的文件进行排序

huangapple go评论59阅读模式
英文:

VB.net framework 4.8 : How to sort files in a folder by creation date

问题

我正在寻找如何获取文件夹中最后创建的文件的名称。我使用.NET Framework 4.8。

使用以下代码行,我可以获取文件夹中所有文件的名称,但我不知道如何按创建日期对它们进行排序。

System.IO.DirectoryInfo("c:\\Parametre").GetFileSystemInfos()

(我正在使用Aveva ArchestrA,这似乎不像Visual Studio一样灵活作为开发环境。)

英文:

I'm looking for how to get the name of the last file created in a folder. I work in .net framework 4.8.

With the following line of code I can get the name of all the files in the folder but I don't know how to sort them by creation date.

'System.IO.DirectoryInfo("c:\Parametre").GetFileSystemInfos()'

(I am using Aveva ArchestrA, which does not seem to be as flexible as Visual Studio as a development environment.)

答案1

得分: 2

你可以创建一个变量来存储找到的最新日期,并将其初始化为可能的最小值。然后,你可以迭代所有的文件,检查每个文件是否创建日期晚于你存储的日期,如果是的话,就更新最新日期并记住文件名,如下所示:

Dim dir As String = "C:\Parametre"

Dim latestFilename As String = ""
Dim latestDatetime As DateTime = DateTime.MinValue

Dim di As IO.DirectoryInfo = New System.IO.DirectoryInfo(dir)
For Each fi As IO.FileInfo In di.GetFiles()
    If fi.CreationTimeUtc > latestDatetime Then
        latestDatetime = fi.CreationTimeUtc
        latestFilename = fi.FullName
    End If
Next

(理论上,尽管不太可能,可能存在多个具有相同的最新创建时间戳的文件,上述代码将仅返回文件系统中记录的第一个文件。)

英文:

You can make a variable to hold the latest date found and initialize it to the minimum value possible. Then you iterate over all the files and see if each one has a created date later than the date you've stored, and if so then you update the latest date and remember the filename, like this:

Dim dir As String = "C:\Parametre"

Dim latestFilename As String = ""
Dim latestDatetime As DateTime = DateTime.MinValue

Dim di As IO.DirectoryInfo = New System.IO.DirectoryInfo(dir)
For Each fi As IO.FileInfo In di.GetFiles()
    If fi.CreationTimeUtc > latestDatetime Then
        latestDatetime = fi.CreationTimeUtc
        latestFilename = fi.FullName
    End If
Next


' The variable latestFilename now contains the full name of
' the file with the latest creation date in the directory dir.

(Theoretically, although unlikely, there could be more than one file with the same latest creation timestamp, the above code will return only the first one that is recorded in the file system.)

huangapple
  • 本文由 发表于 2023年4月19日 16:53:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76052538.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定