public static void MapWorkingFolder(Options options) { if (!options.ConnectWorkingFolderAsNetworkDrive) { return; } NativeMethods.NETRESOURCE resource = new NativeMethods.NETRESOURCE() { dwType = NativeMethods.RESOURCETYPE_DISK, lpRemoteName = options.WorkingFolder, }; uint error = NativeMethods.WNetAddConnection2(ref resource, options.NetworkDrivePassword, options.NetworkDriveUserName, NativeMethods.CONNECT_TEMPORARY); if (error != 0) { throw new InvalidOperationException($"Failed to connect network drive. Error code {error}"); } }
private void CopyFiles(string[] sourceFilesToCopy, string destinationShare) { NativeMethods.NETRESOURCE nr = new NativeMethods.NETRESOURCE(); nr.dwType = NativeMethods.ResourceType.RESOURCETYPE_DISK; nr.lpLocalName = null; nr.lpRemoteName = destinationShare; nr.lpProvider = null; int retCode = NativeMethods.WNetAddConnection2(nr, Favorite.Password, Favorite.Credential.IsSetUserNameAndDomainName ? Favorite.Credential.UserNameWithDomain : Favorite.Credential.UserName, 0); if (retCode != 0) { string errorMessage = "Terminals was unable to copy your file" + (sourceFilesToCopy.Length > 1 ? "s" : "") + " to the server."; Log.Error(errorMessage, new Exception("WNetAddConnection2 error return code: " + retCode)); MessageBox.Show(errorMessage, "File copy", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string result = "Your files have been copied to:" + Environment.NewLine; foreach (string sourceFileToCopy in sourceFilesToCopy) { try { string destination = Path.Combine(destinationShare, Path.GetFileName(sourceFileToCopy)); File.Copy(sourceFileToCopy, destination, true); result += Environment.NewLine + destination; } catch (Exception ex) { Log.Error("There's been a problem copying your drag&drop file '" + sourceFileToCopy + "' to the server", ex); } } Log.Info(result); MessageBox.Show(result, "Copy result", MessageBoxButtons.OK, MessageBoxIcon.Information); NativeMethods.WNetCancelConnection2(destinationShare, 0, true); }
public static void MountNetworkLocation(string localDriveName, string remotePath, string username, string password, bool promptUser) { localDriveName = FileManager.GetDriveLetter(localDriveName); var resource = new NativeMethods.NETRESOURCE { dwType = NativeMethods.ResourceType.DISK, lpLocalName = localDriveName, lpRemoteName = remotePath, lpProvider = null }; int ret = NativeMethods.WNetUseConnection( IntPtr.Zero, resource, promptUser ? null : password, promptUser ? null : username, promptUser ? NativeMethods.Connect.INTERACTIVE | NativeMethods.Connect.PROMPT : 0, null, null, null); if (ret != NO_ERROR) { throw new Win32Exception(ret); } }