How to "DIR" a network resource for shares?

Say for instance, I want to create my own flavor of drive mapping utility with browser integrated into my application.

Instead of going to network neighborhood, I would much rather want it to be able to just type the network computer name and have it show me the shares from which to click on to then map as the selected drive letter.

Does anyone have the API or other Function Declaration/Call for setting this up?  Ideally I suppose I also need the code for doing the DIR of the network neighborhood so in the event they dont know the name of the server they could browse it but I could really just invoke the "map by dialog" if they dont know the name but it would also be nice if you know how to do that as well :)
Who is Participating?
MirkwoodConnect With a Mentor Commented:
Advanced_TechAuthor Commented:
Edited text of question.
This will do it. 


Option Explicit

Private Declare Function WNetAddConnection Lib "mpr.dll" Alias "WNetAddConnectionA" (ByVal lpszNetPath As String, ByVal lpszPassword As String, ByVal lpszLocalName As String) As Long
Private Declare Function WNetCancelConnection Lib "mpr.dll" Alias "WNetCancelConnectionA" (ByVal lpszName As String, ByVal bForce As Long) As Long

Const WN_Success = &H0
Const WN_Not_Supported = &H1
Const WN_Net_Error = &H2
Const WN_Bad_Pointer = &H4
Const WN_Bad_NetName = &H32
Const WN_Bad_Password = &H6
Const WN_Bad_Localname = &H33
Const WN_Access_Denied = &H7
Const WN_Out_Of_Memory = &HB
Const WN_Already_Connected = &H34

'-- Error number and message
Public ErrorNum         As Long
Public ErrorMsg         As String

Public rc               As Long


   dwScope        As Long
   dwType         As Long
   dwDisplayType  As Long
   dwUsage        As Long
   lpLocalName    As String
   lpRemoteName   As String
   lpComment      As String
   lpProvider     As String
End Type


'Allows the caller to redirect (connect) a local
'device to a network resource. It is similar to
'WNetAddConnection, except that it takes a pointer
'to a NETRESOURCE structure to describe the network
'resource to connect to. It also takes the addition
'parameters lpUserID and dwFlags.

'Specifies the network resource to connect to.
'The following fields must be set when making a
'connection, the others are ignored.

'  lpRemoteName: Specifies the network resource
'                to connect to. This is limited
'                to MAX_PATH.
'  lpLocalName: This specifies the name of a local
'               device to be redirected, such as "F:"
'               or "LPT1". The string is treated in a
'               case insensitive manner, and may be
'               the empty string (or NULL) in which
'               case a connection to the network resource
'               is made without making a redirection.
'  lpProvider: Specifies the NP to connect to. If NULL
'              or empty string, Windows will try each
'              NP in turn. The caller should set
'              lpProvider only if it knows for sure
'              which network it wants. Otherwise, it
'              is preferable to let Windows determine
'              which NP the network name maps to.
'              If this is non NULL, Windows will try
'              the named NP and no other.
'  dwType: Specifies the type of resource to connect to.
'          if lpLocalName is not the empty string. It may
'          also be RESOURCETYPE_ANY if lpLocalName is the
'          empty string.
'Specifies the password to be used in making the
'connection, normally the password associated with
'lpUserID. A NULL value or string may be passed in
'to indicate to the function to use the current
'default password.
'This specifies the identity of the user needed to
'make the connection. If NULL, a default will be
'applied. This is used when the user wishes to connect
'to a resource, but has a different user name or
'account assigned to him for that resource. This
'identification represents a security context, and
'is NP specific.
'This is a bit mask which may have any of the
'following bits set:
'  CONNECT_UPDATE_PROFILE: If the connection should
'                          be made persistent. If set,
'                          Windows automatically restores
'                          this connection when the user
'                          logs on to the network. A connection
'                          is only made persistent if the
'                          connection was successful.
Private Declare Function WNetAddConnection2 Lib "mpr.dll" Alias "WNetAddConnection2A" (lpNetResource As NETRESOURCE, ByVal lpPassword As String, ByVal lpUserName As String, ByVal dwFlags As Long) As Long
Private Declare Function WNetCancelConnection2 Lib "mpr.dll" Alias "WNetCancelConnection2A" (ByVal lpName As String, ByVal dwFlags As Long, ByVal fForce As Long) As Long
Private Declare Function WNetConnectionDialog Lib "mpr.dll" (ByVal hWnd As Long, ByVal dwType As Long) As Long
Private Declare Function WNetDisconnectDialog Lib "mpr.dll" (ByVal hWnd As Long, ByVal dwType As Long) As Long


Const NO_ERROR = 0

Public Sub Connect(sDrive As String, sService As String, Optional sPassword As String = "")

   On Error GoTo Err_Connect
   Me.ErrorNum = 0
   Me.ErrorMsg = "" 
   rc = WNetAddConnection(sService & Chr(0), sPassword & Chr(0), sDrive & Chr(0))
   If rc <> 0 Then GoTo Err_Connect

   Exit Sub

   Me.ErrorNum = rc
   Me.ErrorMsg = WnetError(rc)

End Sub

Public Sub DisConnect(sDrive As String)

   On Error GoTo Err_DisConnect
   Me.ErrorNum = 0
   Me.ErrorMsg = "" 
   rc = WNetCancelConnection(sDrive + Chr(0), 0)
   If rc <> 0 Then GoTo Err_DisConnect

   Exit Sub
   Me.ErrorNum = rc
   Me.ErrorMsg = WnetError(rc)

End Sub

Private Function WnetError(Errcode As Long) As String

   Select Case Errcode
      Case WN_Not_Supported:
         WnetError = "Function is not supported."
      Case WN_Out_Of_Memory:
         WnetError = "Out of Memory."
      Case WN_Net_Error:
         WnetError = "An error occurred on the network."
      Case WN_Bad_Pointer:
         WnetError = "The Pointer was Invalid."
      Case WN_Bad_NetName:
         WnetError = "Invalid Network Resource Name."
      Case WN_Bad_Password:
         WnetError = "The Password was Invalid."
      Case WN_Bad_Localname:
         WnetError = "The local device name was invalid."
      Case WN_Access_Denied:
         WnetError = "A security violation occurred."
      Case WN_Already_Connected:
         WnetError = "The local device was connected to a remote resource."
      Case Else:
         WnetError = "Unrecognized Error " + Str(Errcode) + "."
   End Select

End Function

Public Function ConnectNetworkDialog() As Long
   ' *** Show the dialog to map a drive
   'If the function succeeds, the return value is
   'NO_ERROR (0). If the user cancels out of the
   'dialog box, it is &HFFFFFFFF.
   ConnectNetworkDialog = WNetConnectionDialog(0&, RESOURCETYPE_DISK)

End Function

Public Function DisconnectNetworkDialog() As Long
   ' *** Show the dialog to disconnect mapped a drive
   'If the function succeeds, the return value is
   'NO_ERROR (0). If the user cancels out of the
   'dialog box, it is &HFFFFFFFF.
   DisconnectNetworkDialog = WNetDisconnectDialog(0&, RESOURCETYPE_DISK)

End Function

Public Function ConnectPrintDialog() As Long
   ' *** Show the dialog to map a network printer, Windows
   'If the function succeeds, the return value is
   'NO_ERROR (0). If the user cancels out of the
   'dialog box, it is &HFFFFFFFF.
   ConnectPrintDialog = WNetConnectionDialog(0&, RESOURCETYPE_PRINT)

End Function

Public Function DisconnectPrintDialog() As Long
   ' *** Show the dialog to disconnect network printer
   'If the function succeeds, the return value is
   'NO_ERROR (0). If the user cancels out of the
   'dialog box, it is &HFFFFFFFF.
   DisconnectPrintDialog = WNetDisconnectDialog(0&, RESOURCETYPE_PRINT)

End Function

Public Function ConnectUserPassword(sDrive As String, sService As String, Optional sUser As String = "", Optional sPassword As String = "") As Boolean
   ' *** Connect to a network drive
   'attempts to connect to the passed network
   'connection to the specified drive.
   'ErrInfo=NO_ERROR if successful.
   Dim errInfo    As Long
   With NETR
      .lpRemoteName = sDrive
      .lpLocalName = sService
   End With
   errInfo = WNetAddConnection2(NETR, sPassword, sUser, CONNECT_UPDATE_PROFILE)
   ConnectUserPassword = errInfo = NO_ERROR
End Function


Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.


Create a new module, put those declares in it:
'Type definition
Public Type SHITEMID    'Browse Dialog
       cb As Long
       abID As Byte
End Type

Public Type ITEMIDLIST  'Browse Dialog
       mkid As SHITEMID
End Type

Public Type BROWSEINFO  'Browse Dialog
       hOwner As Long
       pidlRoot As Long
       pszDisplayName As String
       lpszTitle As String
       ulFlags As Long
       lpfn As Long
       lParam As Long
       iImage As Long
End Type
Public Const BIF_RETURNONLYFSDIRS = &H1 'Browse Dialog
Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
Declare Function SHBrowseForFolder Lib "shell32.dll" Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long

'PURPOSE:   Displays a dialog that allows the user to select a directory from a tree
'   IN szPrompt:        Prompt to display
'RETURNS:   The path selected, or "" if cancel was selected
Public Function BrowseForFolder(szPrompt As String) As String
       Dim bi As BROWSEINFO
       Dim pidl As Long
       Dim nRet As Long
       Dim szPath As String
       szPath = Space$(512)
       'Fill struct
       bi.hOwner = 0&
       bi.pidlRoot = 0&
       bi.lpszTitle = szPrompt
       bi.ulFlags = BIF_RETURNONLYFSDIRS
       'Display the dialog and get the selected path
       pidl& = SHBrowseForFolder(bi)
       SHGetPathFromIDList ByVal pidl&, ByVal szPath
       'Return value
       BrowseForFolder = Trim$(szPath)
End Function
Here is a complete code.
Create a new exe project with a form and one CommandButton.
Add a reference to "Microsoft Internet Control" (shdocvw.dll).

Option Explicit

Const WSASYS_STATUS_LEN = 128 + 1
Const AF_INET = 2

Private Type WSADATA
    wHighVersion As Long
    szDescription As String * WSADESCRIPTION_LEN
    szSystemStatus As String * WSASYS_STATUS_LEN
    iMaxSockets As Long
    iMaxUdpDg As Long
    lpVendorInfo As Long
End Type

Private Type HOSTENT
    h_name As Long 'LPSTR
    h_aliases As Long 'LPLPSTR
    h_addrtype As Integer
    h_length As Integer
    h_addr_list As Long 'char FAR * FAR * h_addr_list
End Type
Private Type IN_ADDR
    b1 As Byte
    b2 As Byte
    b3 As Byte
    b4 As Byte
End Type
Private Declare Function WSAStartup Lib "Wsock32.dll" (ByVal wVersionRequested As Integer, ByRef lpWSAData As WSADATA) As Long
Private Declare Sub WSACleanup Lib "Wsock32.dll" ()
Private Declare Function gethostbyaddr Lib "Wsock32.dll" (addr As Any, ByVal ilen As Long, ByVal itype As Long) As Long
Private Declare Function inet_addr Lib "Wsock32.dll" (ByVal cp As String) As Long
Private Declare Function gethostbyname Lib "Wsock32.dll" (ByVal name As String) As Long 'HOSTENT

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Declare Function lstrlen Lib "kernel32" Alias "lstrlenA" (ByVal lpString As Long) As Long
Private Declare Function lstrcpy Lib "kernel32" Alias "lstrcpyA" (ByVal lpString1 As String, lpString2 As Any) As Long

Public Function GetName(cpAddr As String) As String
    Dim Adata As WSADATA
    Dim addr As Long
    Dim p As Long
    Dim host As HOSTENT
    Dim buf As String
    GetName = "" 
    If WSAStartup(&H101, Adata) <> 0 Then Exit Function
    addr = inet_addr(cpAddr)
    If addr <> INADDR_NONE Then
        'switch address
        addr = ((addr And &HFF&) * &H1000000) _
            + ((addr And &HFF000000) / &H1000000) _
            + ((addr And &HFF00&) * &H100) _
            + ((addr And &HFF0000) / &H100)
        p = gethostbyaddr(ByVal VarPtr(addr), 4, AF_INET)
        If p Then
            CopyMemory ByVal VarPtr(host), ByVal p, LenB(host)
            buf = Space(lstrlen(host.h_name))
            lstrcpy buf, ByVal host.h_name
            GetName = Trim(Left(buf, lstrlen(host.h_name)))
        End If
    End If

End Function

Public Function GetIPaddress(sName As String) As String
    Dim Adata As WSADATA
    Dim a As IN_ADDR
    Dim host As HOSTENT
    Dim p As Long
    GetIPaddress = "" 
    If WSAStartup(&H101, Adata) <> 0 Then Exit Function
    p = gethostbyname(sName)
    If p Then
        CopyMemory ByVal VarPtr(host), ByVal p, LenB(host)
        'p = host.h_addr_list[0]
        CopyMemory ByVal VarPtr(p), ByVal host.h_addr_list, LenB(p)
        If p Then
            'a = *p
            CopyMemory ByVal VarPtr(a), ByVal p, LenB(a)
            GetIPaddress = a.b1 & "." & a.b2 & "." & a.b3 & "." & a.b4
        End If
    End If

End Function

Private Sub Command1_Click()
    Dim sh As New SHDocVw.Shell
    Dim fd As SHDocVw.Folder
    Set fd = sh.BrowseForFolder(Me.hWnd, "Select a computer", BIF_BROWSEFORCOMPUTER, ssfNETWORK)
    MsgBox fd.Title & "=" & GetIPaddress(fd.Title)
End Sub
I want to list the "Directory of shares" on a named PC on the network which has shared some of its drives.

None of these appear to work to do this.  All good code but none are complete as far as I can tell.  The last one gives me an error

How do we  
"'Add a reference to "Microsoft Internet Control" (shdocvw.dll).'"  
as you say?
for c:\windows\system\shdocvw.dll
I'm Needing the Declaration yes?

Also on the proposed answer I do not see any code which will specifically do as I need.  Is there some secret way of using this to not simply invoke the connect network dialog box?  

I'm not looking to activate the connect network shared device dialog.  I can already do that but I want to be able to recall or type in the Computer name like SERVERX and have it display the shares for me to just click the share instead of navigating and persusing the Network Neighborhood or Entire Network using either Explorer or the Connect Network Device Dialog box which relinquishes control and is a locked style interface...  :(
The only thing the MS Internet Control adds when I add it is the Blue Browser control?
Mirkwood your code appeared promissing but I get

Compile error unknown user defined type?
"Dim sh As New SHDocVw.Shell"
Should I be doing something special with the Internet control seems if I add it only allows me to drop Browser control on forms.  Tried naming browser control SHDocVw same thing of course

I Just Can't believe there is NO simple way to get DIR of shares with regular VB and Controls/DLL's?
Are the new links for anyone else who wants to try these.  

Advanced_TechAuthor Commented:
Rayford is working with me on this we are both trying to puzzle this out together and hoping you can help us.  I'm rejecting this answer not because it is completely wrong but because nothing here gets us what we are looking for just yet and still hoping for an actual working "Answer"

The new CCRP Server Browse dialog will not even allow itself to be brought up with a computer already select and share names listed.  

for example:
    .SelectedFolder = "\\MYSVR-1\"
    .RootFolder = "\\MYSVR-1\"
Brings up the DESKTOP when using objBD.Browse

    .SelectedFolder = "\\MYSVR-1\CSHARE"
    .RootFolder = "\\MYSVR-1\"

Brings up the Contents of the CSHARE FODLER when using objBD.Browse

We need to Bring up the Shares themselves not the network neighborhood for in some companies this is an amazing OCEAN of server names and workstation names!  Nor do we want to be required to KNOW the share names such as CSHARE to be able to get it to display.

    .SelectedFolder = "\\MYSVR-1\CSHARE"
    .RootFolder = "\\MYSVR-1\CSHARE"
is the closest to what we want but what we really want is more like
    .SelectedFolder = "\\MYSVR-1\CSHARE\.."
    .RootFolder = "\\MYSVR-1\CSHARE\.."
if you follow my drift but this does not work either it give us the first entry in the Entire Network browse listing..  Maybe future versions of CCRP will work as expected here.  :(  Help!!

Check project/references
Microsoft Internet Controls
to get

Advanced_TechAuthor Commented:
We have this working now the best input was from Mirkwood please claim your points..
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.