Ismail
Ismail

Reputation: 89

How to check whether a input string is a File name or Folder name using Vbscript

My objective is to find whether the given input is s file name or folder name using Vb script.

For example if user gives "D:\Temp\testfile.docx" then it should navigate to File Related Function, Similarly if user gives "D:\Temp\" then it should navigate to Folder Related Function.

If there is no straightforward solution, Is there any work around to do this ?

Upvotes: 2

Views: 853

Answers (2)

rory.ap
rory.ap

Reputation: 35260

I created this simple function that should suit your needs:

'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

You can test it by creating a file "c:\test" and running `MsgBox(GetTypeOfPath("c:\test"))"; it will return 2. Then delete that file, create a folder "c:\test" and run the same thing; it will return 1. Then delete that and run it a third time; it will return -1.

Upvotes: 1

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

Check whether the user input refers to an existing file (.FileExists) or folder (.FolderExists):

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

If that doesn't fit your needs, ask the user to identify folders by always appending "\" and check Right(userinp, 1).

Upvotes: 1

Related Questions