I am able to connect to a network drive properly using the following C++ code. No user id / password is required to connect to the network drive.
NETRESOURCE netrc;
memset(&netrc, 0, sizeof(netrc));
netrc.dwType = RESOURCETYPE_ANY;
netrc.lpLocalName = NULL;
netrc.lpRemoteName = L"\\\\192.168.68.163\\Storage";
netrc.lpProvider = NULL;
LPWSTR serverPath = netrc.lpRemoteName;
/* Connect to network drive*/
DWORD dwResult = WNetAddConnection2(&netrc, nullptr, nullptr, CONNECT_INTERACTIVE);
if (dwResult == ERROR_SESSION_CREDENTIAL_CONFLICT)
{
dwResult = WNetCancelConnection2W(netrc.lpRemoteName, CONNECT_UPDATE_PROFILE, TRUE);
if (dwResult == NO_ERROR)
{
dwResult = WNetAddConnection2(&netrc, nullptr, nullptr, CONNECT_INTERACTIVE);
}
}
But when I am trying to P/Invoke the same code in a C# program, it does not work. Please find the C# code below
NETRESOURCE netResource = new NETRESOURCE();
netResource.dwType = ResourceType.Any;
netResource.lpRemoteName = @"\\192.168.68.163\Storage";
netResource.lpLocalName = null;
netResource.lpProvider = null;
// result -> 67
var result = WNetAddConnection2(netResource, null, null,0)
if (result != 0 )
{
// result -> 2250
result = WNetCancelConnection2(networkName, 0, true);
if (result == 0)
{
result = WNetAddConnection2(netResource, "", "", 0);
}
}
P/Invoke declarations
[StructLayout(LayoutKind.Sequential)]
public class NETRESOURCE
{
public ResourceScope dwScope = 0;
public ResourceType dwType = 0;
public ResourceDisplaytype dwDisplayType = 0;
public ResourceUsage dwUsage = 0;
public string lpLocalName = null;
public string lpRemoteName = null;
public string lpComment = null;
public string lpProvider = null;
}
public enum ResourceType
{
Any = 0,
Disk = 1,
Print = 2,
Reserved = 8,
}
[DllImport("mpr.dll", CharSet = CharSet.Auto)]
private static extern int WNetAddConnection2(NETRESOURCE netResource,
string password,
string username,
int flags);
[DllImport("mpr.dll", CharSet = CharSet.Auto)]
private static extern int WNetCancelConnection2(string name, int flags, bool force);
Please point out where I am going wrong.
Sujay