private static extern int WNetUseConnection( IntPtr hwndOwner, _NETRESOURCE lpNetResource, string lpPassword, string lpUserID, int dwFlags, string lpAccessName, string lpBufferSize, string lpResult );
public static void WNetUseConnection(string remoteName, string user, string pass) { _NETRESOURCE myStruct = new _NETRESOURCE { dwType = 1, //it's a disk (0 is any, 2 is printer) lpRemoteName = remoteName }; int error = WNetUseConnection(new IntPtr(0), myStruct, pass, user, 0, null, null, null); if (error != 0) { throw new Exception("That didn't work either"); } // if we reach here then everything worked!!! }
public void PublishFiles(IPublishProject project, Uri destination) { var files = project.Files; for (int i = 0; i < files.Count; i++) { var item = files[i]; try { // try copying without impersonating first... CopyOneFile(destination, item); } catch (UnauthorizedAccessException) { var resource = new _NETRESOURCE(); resource.dwType = RESOURCETYPE_DISK; resource.lpRemoteName = Path.GetPathRoot(destination.LocalPath); NetworkCredential creds = null; var res = VsCredentials.PromptForCredentials( JToolsPackage.Instance, destination, new[] { "NTLM" }, "", out creds); if (res != DialogResult.OK) { throw; } var netAddRes = WNetAddConnection3( Process.GetCurrentProcess().MainWindowHandle, ref resource, creds.Password, creds.Domain + "\\" + creds.UserName, 0 ); if (netAddRes != 0) { string msg = Marshal.GetExceptionForHR((int)(((uint)0x80070000) | netAddRes)).Message; throw new Exception("Incorrect user name or password: " + msg); } // re-try the file copy now that we're authenticated CopyOneFile(destination, item); } project.Progress = (int)(((double)i / (double)files.Count) * 100); } }
public static extern uint WNetAddConnection3(IntPtr handle, ref _NETRESOURCE lpNetResource, string lpPassword, string lpUsername, uint dwFlags);
public static extern uint WNetAddConnection3(IntPtr handle, ref _NETRESOURCE lpNetResource, string lpPassword, string lpUsername, uint dwFlags);