tags:

views:

107

answers:

3

How to select path only?

VB 6

I want to select a path only.

Example.

C:\Newfolder \iTDC.mdb - The selected path is appeared in the text box

But I want to take only C:\Newfolder, No need of iTDC.mdb file, How can skip the file.

Need VB 6 CODE Help?

+1  A: 

Quick and dirty

Dim sPath As String

sPath = "C:\Newfolder\iTDC.mdb"

sPath = Left(sPath, InStrRev(sPath, "\"))
Ken Keenan
Be aware that code will raise an error if there is no backslash in the string.
MarkJ
+3  A: 

If you add a reference to the Microsoft Scripting Runtime (using Project->References), then you can use the FileSystemObject to do file-related operations. For example:

Dim oFSO as New FileSystemObject

strFolder = oFSO.GetFolder(strPath)

The FileSystemObject also has other useful methods for composing paths (BuildPath) and for testing for the existence of files, folders, etc. (FileExists, FolderExists).

Gary McGill
+1. It's been a while and I'd forgotten about that better way....
Mitch Wheat
A: 

You can use the PathRemoveFileSpec function, available in every version of Windows from 2000 and 98. Here is a VB6 implementation.

Private Declare Function PathRemoveFileSpec Lib "Shlwapi" _
  Alias "PathRemoveFileSpecW" (ByVal szPath As Long) As Long

'Convert input file path to drive & directory only. (Supports UNC too) '    
Function sPathOnly(ByVal sInput As String) As String
  Dim sWorking As String
  sWorking = sInput
  If (PathRemoveFileSpec(StrPtr(sWorking)) <> 0) Then
    'Call succeeded. Trim trailing Null '
    sPathOnly = sTrimNull(sWorking)
  Else
    sPathOnly = sWorking
  End If
End Function

'Trim trailing null characters (e.g. from a string returned from an API call) '
Function sTrimNull(ByVal sIn As String) As String
  Dim iZeroCharacter As Long
  iZeroCharacter = InStr(sIn, Chr$(0))
  If iZeroCharacter > 0 Then
    sTrimNull = Left$(sIn, iZeroCharacter - 1)
  Else
    sTrimNull = sIn
  End If
End Function

I prefer to avoid the Microsoft Scripting Runtime (including FileSystemObject). In my experience it's occasionally broken on user machines, perhaps because their IT department are paranoid about viruses. There are other useful functions in shlwapi.dll, e.g. for testing whether folders exist or files exist.

MarkJ