Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Map to network drive

Status
Not open for further replies.

kurgan383

IS-IT--Management
Jan 7, 2003
17
US
Can anyone point me in the right direction to map a network drive with vb.net?
 
Here are two ways I can think of:

1. use the 'Windows Script Host Object Model'.
To use this procedure, you need to add a reference (wshom.ocx).

Code:
Sub mapDrive(ByVal strDriveLetter As String, _
             ByVal strShare As String, _
             Optional ByVal bPersistent As Boolean = True)
    Dim myNetwork As IWshRuntimeLibrary.IWshNetwork
    myNetwork = New IWshRuntimeLibrary.IWshNetwork_Class()
    'see below for error checking
    Try
        myNetwork.MapNetworkDrive(strDriveLetter, strShare)
    Catch exc As Exception
        MessageBox.Show(Me, exc.Message.ToString)
    End Try
End Sub

Or,

2. you could shell the NET USE dos command:

Code:
Private Sub MapDrive(ByVal strDriveLetter As String, _
                     ByVal strShare As String, _
                     Optional ByVal bPersistent As Boolean = True)
    If strDriveLetter.Length = 1 AndAlso _
                     IO.Directory.Exists(strShare) Then
        Dim strShellCommand, strPersistent As String
        If bPersistent Then
            strPersistent = "Yes"
        Else
            strPersistent = "No"
        End If
        strShellCommand = "NET USE " & strDriveLetter & _
                          ": " & strShare & _
                          " /PERSISTENT:" & strPersistent
        'shell out the command and
        'wait for up to 1 minute
        Shell(strShellCommand, AppWinStyle.Hide, True, 60000)
    End If
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) _
                          Handles Button1.Click
    MapDrive("G", "\\ComputerName\ShareName", False)
End Sub

Although shorter, the first suggestion requires an interop dll to be distributed with the app (if the app is going to be distributed).


see this FAQ for info on Enumerating Available Shares and Current Mapping: faq184-4449

-Stephen Paszt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top