how to check if a file exists with vbscript

ε祈祈猫儿з 提交于 2020-02-03 04:32:05

问题


I have a folder with many files. It looks like this file1.txt, newFile1.txt, file2.txt, newFile2.txt, file3.txt, newFile3.txt, file4.txt, newFile4.txt, ....

I have a code that generates the newFilei.txt . I want to write a vbscript that checks if a newFile exists in this folder or not. I tried this

Set objFolder = FSO.GetFolder("C:\myFolder\")

For Each objFile In objFolder.Files 
        fileName=objFile.name 
    If instr(fileName,"newFile*") =1 Then
        WScript.Echo "new File exist"
    End If
Next 

but this didnt work. any ideas ?


回答1:


Edit: The COM object made this very simple.

Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")

If fso.FileExists("C:\myFolder\newFile.txt") Then
    'Perform Code
End If

Or, if you wanted your code to work

Set FSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = FSO.GetFolder("C:\myFolder\")
For Each objFile In objFolder.Files 
        fileName=objFile.name 
    If instr(fileName,"newFile") Then
        WScript.Echo "new File found"
    End If
Next 


And, pulling it all together.
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = FSO.GetFolder("C:\myFolder\")
Set objFiles = objFolder.Files 
For i=0 to objFiles.Count
    If FSO.FileExists("C:\myFolder\newFile" & i & ".txt") Then
        WScript.Echo "new File found"
    End If
Next 


来源:https://stackoverflow.com/questions/22387719/how-to-check-if-a-file-exists-with-vbscript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!