Using WNetUseConnection to connect to a network drive

2.2k Views Asked by At

I'm using WNetUseConnection to connect to a network drive, everything was working fine yesterday, below is the code I used to connect to the network drive.

NETRESOURCE nr = new NETRESOURCE();
nr.dwType = RESOURCETYPE_DISK;
nr.lpRemoteName = remote;
nr.lpLocalName = "L:";
int ret = WNetUseConnection(IntPtr.Zero, nr, username, password, 0, null, null, null);

I find the value of remote using the below code

WNetGetConnection("L:", sb, ref size);          
var remote= sb.ToString();

And I cancel the connection using the below code

WNetCancelConnection2("L:", 0, false); 

As I mentioned before everything worked fine yesterday, but today when I tried to retest the code it failed. The WNetGetConnection returned the error 1201 in some cases and 1202 in others (note that the drive was showing an x sign which means it was disconnected)

enter image description here

Trying now to reconnect to the drive using WNetUseConnection and the valid credentials failed with error 1219 which was really weird since there was no established connections to the drive, meanwhile trying to connect to the drive with passing empty username and password work just fine.

Using WNetCancelConnection2 to cancel the connection works and the connection is cancelled successfully but trying to execute WNetUseConnection again to retest the steps throws this error 67 which doesn't make sense since My PC is still showing the drive, but when I try to double click on the drive it shows me the error that the drive doesn't exist.

Disconnect the drive won't work, but remapping the drive to the same location with the same drive letter worked and replaced the network drive. but remapping didn't solve the issue.

When I deleted and recreated the drive using the below commands everything worked fine again.

net use * /del /yes

net use l: "NetworkPath" /user:"username" "password"

Can anyone tells me why this happened? I appreciate the help.

Edit:

The problem started to show more often now, I cannot connect to the drive using the code, but the connection is successfully created when I double click on the drive icon on my computer. The commands are no longer solving the issue.

PS: I'm using windows 10 version 1709

1

There are 1 best solutions below

0
On BEST ANSWER

After using the library for a while I found that adding delays between the connect and disconnect prevents this issue to occur, and in some cases if the user running the WNetUseConnection had a corrupted network connection the error will keep showing and overriding his permissions will solve this issue.

Not sure if this is the right solution, but at least these are the workarounds I used and proved working.