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 VisualStudioTools.Project.NativeMethods._NETRESOURCE(); resource.dwType = VisualStudioTools.Project.NativeMethods.RESOURCETYPE_DISK; resource.lpRemoteName = Path.GetPathRoot(destination.LocalPath); NetworkCredential creds = null; var res = VsCredentials.PromptForCredentials( _serviceProvider, destination, new[] { "NTLM" }, "", out creds); if (res != DialogResult.OK) { throw; } var netAddRes = VisualStudioTools.Project.NativeMethods.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); } }