【问题标题】:how can I check if a file exists?如何检查文件是否存在?
【发布时间】:2011-11-01 23:14:37
【问题描述】:

我想检查一个文件是否存在,如果存在,我想打开它并读取第一行,

如果文件不存在或文件没有内容,那么我想静默失败,不让任何人知道发生了错误。

【问题讨论】:

  • 您是否在任何地方搜索过vbscript file exists
  • @Fionnuala 但这来自谷歌的第一个结果 :D ;)

标签: vbscript wsh


【解决方案1】:

从这里开始:

Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
   msg = path & " exists."
Else
   msg = path & " doesn't exist."
End If

取自documentation

【讨论】:

    【解决方案2】:

    对于正在寻找一种方法来观看 VBS 中存在的特定文件的任何人:

    Function bIsFileDownloaded(strPath, timeout)
      Dim FSO, fileIsDownloaded
      set FSO = CreateObject("Scripting.FileSystemObject")
      fileIsDownloaded = false
      limit = DateAdd("s", timeout, Now)
      Do While Now < limit
        If FSO.FileExists(strPath) Then : fileIsDownloaded = True : Exit Do : End If
        WScript.Sleep 1000      
      Loop
      Set FSO = Nothing
      bIsFileDownloaded = fileIsDownloaded
    End Function
    

    用法:

    FileName = "C:\test.txt"
    fileIsDownloaded = bIsFileDownloaded(FileName, 5) ' keep watching for 5 seconds
    
    If fileIsDownloaded Then
      WScript.Echo Now & " File is Downloaded: " & FileName
    Else
      WScript.Echo Now & " Timeout, file not found: " & FileName 
    End If
    

    【讨论】:

      【解决方案3】:

      现有文件夹将因 FileExists 而失败

      Function FileExists(strFileName)
      ' Check if a file exists - returns True or False
      

      替代或补充使用:

      Function FolderExists(strFolderPath)
      ' Check if a path exists
      

      【讨论】:

      • 这个答案没有回答问题。它也不遵循格式指南。
      猜你喜欢
      • 1970-01-01
      • 2011-10-21
      • 2017-04-24
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多