如何使用Vbscript检查输入字符串是文件名还是文件夹名

时间:2014-11-20 15:26:21

标签: string file input vbscript directory

我的目标是使用Vb脚本查找给定输入是s文件名还是文件夹名。

例如,如果用户给出" D:\ Temp \ testfile.docx"然后它应该导航到文件相关功能, 同样,如果用户给出" D:\ Temp \"然后它应该导航到文件夹相关功能。

如果没有直接的解决方案,有没有解决方法呢?

2 个答案:

答案 0 :(得分:1)

检查用户输入是否引用现有文件(。FileExists)或文件夹(。FolderExists):

If FolderExists(userinp) Then 
   folderaction
Else
   If FileExists(userinp) Then
      fileaction
   Else
      handle bad user input
   End If
End If

如果这不符合您的需求,请让用户通过附加" \"来识别文件夹。并检查Right(userinp,1)。

答案 1 :(得分:1)

我创建了这个适合您需求的简单功能:

'Return 1 if the provided path is a folder, 2 if it's a file, and -1 if it's neither.
Function GetTypeOfPath(strToTest)
    Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")

    If(objFSO.FolderExists(strToTest)) Then
        GetTypeOfPath = 1
    ElseIf(objFSO.FileExists(strToTest)) Then
        GetTypeOfPath = 2
    Else 'neither
        GetTypeOfPath = -1
    End If
End Function

您可以通过创建文件“c:\ test”并运行`MsgBox(GetTypeOfPath(“c:\ test”))“来测试它;它将返回2.然后删除该文件,创建一个文件夹”c: \ test“并运行相同的东西;它将返回1.然后删除它并第三次运行;它将返回-1。