Adding a mapped drive with WNetAddConnection2 is not accessible

3.5k views Asked by At

I'm trying to map a drive using WNetAddCOnnection2 but there's something not quite right. The code that I am using from pinvoke.net and seems to work at first. If I am stepping through the code I get a 0 for a response and I am able to use System.IO.Directory.GetFiles() to inspect the new mapped drive which leads me to believe that credentials are fine.

The problem is that the drive is not available outside of the application. When I type net use from a command prompt I see the drive listed like this:

Unavailable  L:        \\<server>\<share>          Microsoft Windows Network

When I try to access the drive I get either:

The system cannot find the drive specified.

or

The system cannot find the path specified.

Any help would be greatly appreciated.

Here's the nutshell of the code in question:

NETRESOURCE res = new NETRESOURCE();
res.iScope = RESOURCE_GLOBALNET;
res.iType = RESOURCETYPE_DISK;
res.iDisplayType = RESOURCEDISPLAYTYPE_SHARE;
res.iUsage = RESOURCEUSAGE_CONNECTABLE;
res.sRemoteName = share;
res.sLocalName = drive;
res.sProvider = null;

int iFlags = 0;
iFlags = CONNECT_UPDATE_PROFILE;

int iResult = WNetAddConnection2( ref res, psPassword, psUsername, iFlags );

The iResult always ends up equaling 0.

1

There are 1 answers

0
Qwertster On

MSDN articles that may assist:
* WNetAddConnection2 - [http://msdn.microsoft.com/en-us/library/aa385413%28VS.85%29.aspx][1]
* NETRESOURCE - [http://msdn.microsoft.com/en-us/library/aa385353%28VS.85%29.aspx][2]

I reckon your problem is the display type where "res.iDisplayType = RESOURCEDISPLAYTYPE_SHARE". Perhaps try changing to a value of "0" (RESOURCEDISPLAYTYPE_GENERIC). So for example, what I generally use to map drives appears:


With Res  
  .dwScope = RES_SCOPE_GLOBALNET 'value 2  
  .dwType = RES_TYPE_DISK 'value of 1  
  .dwUsage = RES_USE_CONNECT 'value of 1  
  .localName = "x:" 'leave blank for no drive   
  .RemoteName = "\\\"  
End With 
lRes = WNetAddConnection2(Res, sPassword, sDomain & "\" & sPassword, RES_CNN_UPDATE_PROFILE) 
If lRes = 0 Then
  'Success 
Else   
  'Error 
End If

Always check your connections before & after calls from command prompt:

1a) From system making connection, list current connections:

   net use

1b) From system connected too, list current sessions:

   net session

To disconnect session, use API 'WNetCancelConnection2', my code following from above:


sServer = "\\\"
lRes = WNetCancelConnection2(sServer, RES_CNN_UPDATE_PROFILE, True)
If lRes `> 0 Then 
  'Success
Else
  'Error
End If

Alternatively, simply making connections using 'net' command:

1) To map a drive letter:

  net use `: \\`\` /user:`\` `

2) To map an IPC connection:

  net use \\`\` /user:`\` `

Disconnecting using 'net' command:

1) Disconnecting mapped drive:

  net use `: /delete

2) Disconnecting server share:

  net use \\`\` /delete