【问题标题】:Can I use FileSystemObject get a single file from a folder using its index?我可以使用 FileSystemObject 使用其索引从文件夹中获取单个文件吗?
【发布时间】:2016-04-06 06:21:27
【问题描述】:

如果一个文件夹中只有一个文件,我是否可以在不知道知道其名称或遍历文件夹中的文件的情况下将其取出?

(代码是 VBS,但它可以是任何东西,FSO 是这里有趣的部分。)

这对我不起作用:

dim fso
set fso = CreateObject("Scripting.FileSystemObject")
dim myFolder
Set myFolder = fso.getFolder("E:\test")
Dim myfiles
Set myfiles = myFolder.Files

WScript.Echo myfiles.Item(0).Path

WScript.Echo myfiles(0).Path 也没有工作。 (索引 0,1 已测试,均失败。)

使用 for each 只获取一个文件似乎有点过头了。另外,我不应该以某种方式使用简单的For 循环而不是For Each 进行迭代吗?所以必须有索引...我似乎找不到它们。

【问题讨论】:

    标签: vbscript filesystemobject fso


    【解决方案1】:

    不,您不能在不知道文件名称或遍历文件夹中的文件的情况下选择文件,至少不能使用 FileSystemObject 实例。作为documented Files 集合的Item 属性需要一个项目的名称,而不是它的索引:

    项目属性(文件)

    获取文件对象中的指定项

    语法

    object.Item(key)[ = newitem]
    

    参数

    对象
    必需的。 File 对象的名称。

    规格
    必需的。项目的名称。

    并非每个集合都允许按索引访问。

    如果您正在寻找魔术,您可以这样做:

    dir = "C:\your\folder"
    
    Set sh = CreateObject("WScript.Shell")
    Set ex = sh.Exec("cmd /c dir /b """ & dir & """")
    While ex.Status = 0 : WScript.Sleep 100 : Wend
    
    filename = Split(ex.StdOut.ReadAll, vbNewLine)(0)
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.GetFile(fso.JoinPath(dir, filename))
    

    然而,这种方法既不是很优雅也不是很健壮,我看不出它比类似的方法有优势

    dir = "C:\your\folder"
    Set fso = CreateObject("Scripting.FileSystemObject")
    For Each item In fso.GetFolder(dir).Files
      Set f = item
    Next
    

    【讨论】:

    • 哇。所以我什至不能使用简单的 For 循环,只能使用 For Each。谢谢。我会暂时打开这个,也许有人有一个魔术。
    【解决方案2】:

    正如您想象的那样,使用 Shell 对象是可能的。

    dim shellApp
    set shellApp = CreateObject("Shell.Application")
    dim myFolder
    Set myFolder = shellApp.NameSpace("E:\test")
    Dim myfiles
    Set myfiles = myFolder.Items 'also contains subfolders
    
    WScript.Echo myfiles.Item(0).Path
    
    'and for loop
    Dim i
    For i = 0 To myfiles.Count - 1
        WScript.Echo myfiles.Item(i).Path
    Next
    

    【讨论】:

      【解决方案3】:

      如果您确定文件夹中只有一个文件,只需一行代码即可:

      Set MyFile = FSO.GetFile("E:\test\" & Dir("E:\test\"))

      ...至少它在 Excel VBA 中对我有用。

      【讨论】:

      • 好主意!不幸的是,Dir 命令在 VBS 中不能这样工作。谢谢你的想法,很好。 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多