Mi e’ capitato, durante la realizzazione di un software ‘di servizio’, di dover far ‘mappare’ un unita’ di rete al software e fargli copiare un file sulla suddetta unita’ .

Non volendo optare per uno ‘sporco’ shell “net use… ho fatto qualche ricerca tra le API di windows:

[sourcecode language=”vb”]

Public 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

[/sourcecode]

Questa funzione permette di connettere un’unita’ di rete

[sourcecode language=”vb”]

Public Declare Function WNetCancelConnection2 Lib “mpr.dll” Alias

“WNetCancelConnection2A” (ByVal lpName As String, ByVal dwFlags As Long, ByVal

fForce As Long) As Long

[/sourcecode]

Questa invece viene utilizzata per disconnettere l’unita’ .

A questo punto il passo e’ breve:

Creo un nuovo modulo, dichiaro qualche costante, le API e due funzioni per sfruttarle:

[sourcecode language=”vb”]

Option Explicit

Const CONNECT_UPDATE_PROFILE = &H1

Const RESOURCE_CONNECTED As Long = &H1

Const RESOURCE_GLOBALNET As Long = &H2

Const RESOURCETYPE_DISK As Long = &H1

Const RESOURCEDISPLAYTYPE_SHARE& = &H3

Const RESOURCEUSAGE_CONNECTABLE As Long = &H1

Declare Function WNetAddConnection2 Lib “mpr.dll” _

Alias “WNetAddConnection2A”

(lpNetResource As NETCONNECT, _

ByVal lpPassword As String, ByVal lpUserName

As String, _

ByVal dwFlags As Long) As Long

Declare Function

WNetCancelConnection2 Lib “mpr.dll” _

Alias “WNetCancelConnection2A” (ByVal

lpName As String, _

ByVal dwFlags As Long, _

ByVal fForce As Long) As

Long

Type NETCONNECT

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

Public Function DisconnectDrive(LocalDrive As String) As

Boolean

Dim NetR As NETCONNECT

‘Utilizzo:

‘DisconnectDrive “Q:”

DisconnectDrive =

(WNetCancelConnection2(LocalDrive, 0, 1))

End Function

Function MapDrive(LocalDrive As String, _

RemoteDrive As

String, Optional Username As String, _

Optional Password As String) As

Boolean

‘Utilizzo:

‘MapDrive “Q:”,

“RemoteMachineRemoteDirectory”,”MyLoginName”, “MyPassword”

Dim

NetR As NETCONNECT

NetR.dwScope = RESOURCE_GLOBALNET

NetR.dwType

= RESOURCETYPE_DISK

NetR.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE

NetR.dwUsage = RESOURCEUSAGE_CONNECTABLE

NetR.lpLocalName = Left$(LocalDrive, 1) & “:”

NetR.lpRemoteName = RemoteDrive

MapDrive = (WNetAddConnection2(NetR, Username, Password, CONNECT_UPDATE_PROFILE) = 0)

End Function

[/sourcecode]

A questo punto, la copia del file risulta semplice, utilizzando il comando

FileCopy [origine], [destinazione]