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 derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

map network share from service

Status
Not open for further replies.

btaber

Programmer
Joined
May 26, 2002
Messages
307
Location
US
Is it possible to map a network share to a drive letter from a windows service?
 
I use the in my services.
Private Sub OnTimedEvent(ByVal source As Object, ByVal e As ElapsedEventArgs)

UnMapDrive("P")
If Not MapDrive("P", mstrQuasarFileLocation, _
"username", "password") Then
EventLog1.WriteEntry("Unable to map drive")
UnMapDrive("P")
End If

End Sub

Public Function MapDrive(ByVal DriveLetter As String, _
ByVal UNCPath As String, _
ByVal strUsername As String, _
ByVal strPassword As String) As Boolean

Dim nr As NETRESOURCE

nr = New NETRESOURCE
nr.lpRemoteName = UNCPath
nr.lpLocalName = DriveLetter & ":"
strUsername = strUsername
strPassword = strPassword
nr.dwType = RESOURCETYPE_DISK

Dim result As Integer
result = WNetAddConnection2(nr, strPassword, strUsername, 0)

If result = 0 Then
Return True
Else
Return False
End If
End Function

Public Function UnMapDrive(ByVal DriveLetter As String) As Boolean
Dim rc As Integer
rc = WNetCancelConnection2(DriveLetter & ":", 0, ForceDisconnect)

If rc = 0 Then
Return True
Else
Return False
End If

End Function


 
You also need this in the class where the map drive function is

Public Declare Function WNetAddConnection2 Lib "mpr.dll" Alias "WNetAddConnection2A" _
(ByRef lpNetResource As NETRESOURCE, ByVal lpPassword As String, _
ByVal lpUserName As String, ByVal dwFlags As Integer) As Integer
Public Declare Function WNetCancelConnection2 Lib "mpr" Alias "WNetCancelConnection2A" _
(ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Integer) As Integer

'<StructLayout(LayoutKind.Sequential)> _
Public Structure NETRESOURCE
Public dwScope As Integer
Public dwType As Integer
Public dwDisplayType As Integer
Public dwUsage As Integer
Public lpLocalName As String
Public lpRemoteName As String
Public lpComment As String
Public lpProvider As String
End Structure
Public Const ForceDisconnect As Integer = 1
Public Const RESOURCETYPE_DISK As Long = &H1
 
Tried this, but it does not work. The result is error 1312, which is "A specified logon session does not exist". Now this kind of makes sense, since a windows service does not have a logged in user. Is there a way to start a login session for a service?
 
Never mind, figured it out. I needed to have the service logon as a user, not local system account. Thanks for the help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top