在VBScript中,我希望获得按创建日期排序的文件夹中的文件列表。我看到,为了做到这一点,我需要要么使用一个记录集(对我来说似乎有点过分),要么自己对集合进行排序(我认为我可以避免这种情况,并且我希望我的代码更短)。
因为我是创建文件的人,所以我使用以日期(yyyy_mm_dd)开头的名称来创建它们,所以我认为如果我可以获得至少按名称排序的文件,那么我就一切都准备好了。不幸的是,MSDN documentation of the Files collection from FileSystemObject没有说明集合的顺序。有没有人知道一些其他的秘密文件或类似的东西,可以更具体?
发布于 2013-06-03 19:34:49
如果您想以特定的顺序获取文件夹中的文件,则必须自己完成。如果您不喜欢ADO记录集或使用可排序的.NET集合,您可以外壳(.Run,.Exec)并处理dir /A:-D /B /O:D /T:C的输出(无文件夹,无格式(无标题/摘要),顺序:日期,时间域:创建)。
更新:
虽然我肯定可以展示.Files集合按名称排序的元素的示例,但盖茨先生显式地使用says
信息: FileSystemObject的限制...无法对files集合中的文件名进行排序-您可以循环访问Files集合中的file对象以获取文件夹中的文件列表。但是,不对文件对象进行排序。需要使用排序例程对Files集合中的File对象进行排序。
简约的演示代码显示:如果您想要使用shell特性,就需要一个shell (%comspec%) --比如intrinsic commands
Option Explicit
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
Dim goWS : Set goWS = CreateObject("WScript.Shell")
Dim csDir : csDir = "c:\temp"
WScript.Quit demoSF()
Function demoSF()
demoSF = 0
Dim aDSOrd : aDSOrd = getDSOrd(csDir, "%comspec% /c dir /A:-D /B /O:D /T:C """ & csDir & """")
Dim oFile
For Each oFile In aDSOrd
WScript.Echo oFile.DateCreated, oFile.Name
Next
End Function ' demoSF
Function getDSOrd(sDir, sCmd)
Dim dicTmp : Set dicTmp = CreateObject("Scripting.Dictionary")
Dim oExec : Set oExec = goWS.Exec(sCmd)
Do Until oExec.Stdout.AtEndOfStream
dicTmp(goFS.GetFile(goFS.BuildPath(sDir, oExec.Stdout.ReadLine()))) = Empty
Loop
If Not oExec.Stderr.AtEndOfStream Then
WScript.Echo "Error:", oExec.Stderr.ReadAll()
End If
getDSOrd = dicTmp.Keys()
End Function输出:
cscript 16895525.vbs
07.10.1998 15:31:34 TlbInf32.chm
..
09.10.2008 22:40:29 sqlce.sql
09.10.2008 22:40:29 gltsqlcopytest.sdf
05.11.2008 20:11:39 Vorfuehrung.class
..
28.03.2011 20:23:36 Program.cs
.
01.10.2012 10:10:10 KyXHDe.chm发布于 2013-06-05 01:18:05
排序的代码真的太多了吗?
set fso = CreateObject("Scripting.FileSystemObject")
Set outputLines = CreateObject("System.Collections.ArrayList")
for each f in fso.GetFolder(".").files
outputLines.Add f.Name
next
outputLines.Sort() ' 5 lines...
For Each outputLine in outputLines
set file = fso.GetFolder(".").files.item (outputLine&"")
Wscript.Echo file.name ' TODO: your thing here
Nexthttps://stackoverflow.com/questions/16895525
复制相似问题