The reason is this:
You pulled the p / invoke signature from pinvoke.net and you did not confirm it. The fool who originally wrote this p / invoke code example had no idea what he was doing, and created one that "works" on 32-bit systems but does not work on 64-bit systems. He somehow turned a very simple p / invoke signature into some kind of surprisingly complicated mess, and it spread like wildfire on the net.
Correct Signature:
[DllImport( "NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern uint NetUseAdd( string UncServerName, UInt32 Level, ref USE_INFO_2 Buf, out UInt32 ParmError ); [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Unicode )] public struct USE_INFO_2 { public string ui2_local; public string ui2_remote; public string ui2_password; public UInt32 ui2_status; public UInt32 ui2_asg_type; public UInt32 ui2_refcount; public UInt32 ui2_usecount; public string ui2_username; public string ui2_domainname; }
And your code should read:
USE_INFO_2 info = new USE_INFO_2(); info.ui2_local = null; info.ui2_asg_type = 0xFFFFFFFF; info.ui2_remote = remoteUNC; info.ui2_username = username; info.ui2_password = password; info.ui2_domainname = domainName; uint paramErrorIndex; uint returnCode = NetUseAdd(null, 2, ref info, out paramErrorIndex); if (returnCode != 0) { throw new Win32Exception((int)returnCode); }
Hope this helps. I just spent half a day on the knee of deep remote debugging of someone elses trash code, trying to figure out what was going on, and that was it.
source share