public void Map(string username, string password, string localDrive, string shareName) { NetResource netResource = new NetResource { Scope = 2, Type = RESOURCETYPE_DISK, DisplayType = 3, Usage = 1, RemoteName = shareName, LocalDrive = localDrive }; try { this.UnMap(localDrive); } catch { Debug.WriteLine("Unable to unmap drive."); } int returnValue = WNetAddConnection(ref netResource, password, username, flags: 0); if (returnValue > 0) { throw new System.ComponentModel.Win32Exception(returnValue); } }
public NetworkConnection(string networkName, System.Net.NetworkCredential credentials) { _networkName = networkName; var netResource = new NetResource() { Scope = ResourceScope.GlobalNetwork, ResourceType = ResourceType.Disk, DisplayType = ResourceDisplaytype.Share, RemoteName = networkName }; var userName = string.IsNullOrEmpty(credentials.Domain) ? credentials.UserName : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName); var result = WNetAddConnection2( netResource, credentials.Password, userName, 0); if (result != 0) { throw new System.ComponentModel.Win32Exception(result, "Error connecting to remote share"); } }
internal NetworkConnection(NetResource resource, NetworkCredential credentials) { _networkName = resource.RemoteName; var userName = string.IsNullOrEmpty(credentials.Domain) ? credentials.UserName : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName); var result = WNetAddConnection2(resource, credentials.Password, userName, 0); if (result != 0) { throw new Win32Exception(result, "Error connecting to remote share " + result); } }
/// <summary> /// 为网络共享做本地映射 /// </summary> /// <param name="username">访问用户名(windows系统需要加计算机名,如:comp-1/user-1)</param> /// <param name="password">访问用户密码</param> /// <param name="remoteName">网络共享路径(如://192.168.0.9/share)</param> /// <param name="localName">本地映射盘符</param> /// <returns></returns> public static uint WNetAddConnection(string username, string password, string remoteName, string localName) { NetResource netResource = new NetResource(); netResource.dwScope = 2; netResource.dwType = 1; netResource.dwDisplayType = 3; netResource.dwUsage = 1; netResource.lpLocalName = localName; netResource.lpRemoteName = remoteName.TrimEnd('\\'); uint result = WNetAddConnection2(netResource, password, username, 0); return result; }
public void LoginToShare(string serverName, string shareName, string user, string password) { string destinationDirectory = string.Format(@"\\{0}\{1}", serverName, shareName); NetResource nr = new NetResource(); nr.iScope = 2; nr.iType = RESOURCETYPE_DISK; nr.iDisplayType = 3; nr.iUsage = 1; nr.sRemoteName = destinationDirectory; nr.sLocalName = null; int flags = 0; int rc = WNetAddConnection2A(ref nr, password, user, flags); if (rc != 0) throw new Win32Exception(rc); }
/// <summary> /// Initializes a new instance of the <see cref="NetworkConnection"/> class. /// </summary> /// <param name="networkName"> /// The full path of the network share. /// </param> /// <param name="credentials"> /// The credentials to use when connecting to the network share. /// </param> public NetworkConnection(string networkName, NetworkCredential credentials) { _networkName = networkName; var netResource = new NetResource { Scope = ResourceScope.GlobalNetwork, ResourceType = ResourceType.Disk, DisplayType = ResourceDisplaytype.Share, RemoteName = networkName.TrimEnd('\\') }; var result = WNetAddConnection2( netResource, credentials.Password, credentials.UserName, 0); if (result != 0) { throw new Win32Exception(result); } }
public void AddConnection(object ip) { var netResource = new NetResource() { Scope = ResourceScope.GlobalNetwork, ResourceType = ResourceType.Disk, DisplayType = ResourceDisplaytype.Share, RemoteName = "\\\\" + (string)ip + "\\C" }; var result = WNetAddConnection2( netResource, null, null, 0x00000004 | 0x00000008 | 0x1000); if (result != 0) { Console.WriteLine("Result not zero: " + result); } }
public bool WNetAddConnection(string LocalDrive, string NetworkFolderPath, string User, string Password, bool Force) { bool success = false; try { NetResource netresource = new NetResource(); netresource.Scope = RESOURCE_GLOBALNET; netresource.Type = RESOURCETYPE_DISK; netresource.Usage = RESOURCEUSAGE_CONNECTABLE; netresource.DisplayType = RESOURCEDISPLAYTYPE_SHARE; netresource.LocalName = LocalDrive; netresource.RemoteName = NetworkFolderPath; netresource.Comment = ""; netresource.Provider = ""; int Flag = CONNECT_UPDATE_PROFILE; if (Force) { success = WNetCancelConnection(LocalDrive, true); } int result = WNetAddConnection2A(ref netresource, Password, User, Flag); if (result > 0) { throw new System.ComponentModel.Win32Exception(result); } success = true; } catch //(Exception e) { //lib.Echo("Error: " + e.Message, myLib.MsgType.FAIL); } return success; }
public NetworkConnection(string networkName, NetworkCredential credentials) { _networkName = networkName; if (!_networkName.Contains("\\\\")) { return; } var netResource = new NetResource() { Scope = ResourceScope.GlobalNetwork, ResourceType = ResourceType.Disk, DisplayType = ResourceDisplaytype.Share, RemoteName = networkName.TrimEnd('\\') }; //var userName = string.IsNullOrEmpty(credentials.Domain)? credentials.UserName: string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName); //using (new NetworkConnection(@"\\server\read", readCredentials)) //using (new NetworkConnection(@"\\server2\write", writeCredentials)) //{ // File.Copy(@"\\server\read\file", @"\\server2\write\file"); //} var result = WNetAddConnection2( netResource, credentials.Password, credentials.UserName, 0); if (result != 0) { throw new Win32Exception(result, "Error connecting to remote share"); } }
private static extern uint WNetAddConnection2(NetResource lpNetResource, string lpPassword, string lpUsername, uint dwFlags);
private void EnumerateServers(NetResource pRsrc, ResourceScope scope, ResourceType type, ResourceUsage usage, ResourceDisplayType displayType, string kPath) { uint bufferSize = 16384; var buffer = Marshal.AllocHGlobal((int)bufferSize); IntPtr handle; uint cEntries = 1; var serverenum = false; var result = WNetOpenEnum(scope, type, usage, pRsrc, out handle); if (result == ErrorCodes.NO_ERROR) { do { result = WNetEnumResource(handle, ref cEntries, buffer, ref bufferSize); if ((result == ErrorCodes.NO_ERROR)) { Marshal.PtrToStructure(buffer, pRsrc); if (kPath == "") { if ((pRsrc.dwDisplayType == displayType) || (pRsrc.dwDisplayType == ResourceDisplayType.RESOURCEDISPLAYTYPE_DOMAIN)) _aData.Add(pRsrc.lpRemoteName + "|" + pRsrc.dwDisplayType); if ((pRsrc.dwUsage & ResourceUsage.RESOURCEUSAGE_CONTAINER) == ResourceUsage.RESOURCEUSAGE_CONTAINER) if ((pRsrc.dwDisplayType == displayType)) EnumerateServers(pRsrc, scope, type, usage, displayType, kPath); } else { if (pRsrc.dwDisplayType == displayType) { _aData.Add(pRsrc.lpRemoteName); EnumerateServers(pRsrc, scope, type, usage, displayType, kPath); serverenum = true; } if (!serverenum) { if (pRsrc.dwDisplayType == ResourceDisplayType.RESOURCEDISPLAYTYPE_SHARE) _aData.Add(pRsrc.lpRemoteName + "-share"); } else serverenum = false; if ((kPath.IndexOf(pRsrc.lpRemoteName) >= 0) || (String.Compare(pRsrc.lpRemoteName, "Microsoft Windows Network") == 0)) EnumerateServers(pRsrc, scope, type, usage, displayType, kPath); } } else if (result != ErrorCodes.ERROR_NO_MORE_ITEMS) break; } while (result != ErrorCodes.ERROR_NO_MORE_ITEMS); WNetCloseEnum(handle); } Marshal.FreeHGlobal(buffer); }
public string[] LoadFiles(string currentPathRoot) { List <string> filesFound = new List <string>(); foreach (var ext in App.Extensions) { string extension = ext.Trim(); if (extension == null) { extension = ""; } if (extension.Length > 1) { if (extension[0] != '.') { extension = "*." + extension; } else { extension = "*" + extension; } } else { string errorMessage = "Could not find an extension to file filter."; Log.WriteError(errorMessage); throw new Exception(errorMessage); } try { string[] ff = Directory.GetFiles(currentPathRoot, extension); foreach (string dir in ff) { Log.WriteInformation(string.Format("FOUND file {0}", dir)); } filesFound.AddRange(ff); } catch (Exception) { if (currentPathRoot.StartsWith("\\\\") && !string.IsNullOrEmpty(App.Username)) { NetResource resource = new NetResource(); resource.dwType = ResourceType.RESOURCETYPE_DISK; resource.lpLocalName = null; resource.lpRemoteName = currentPathRoot; resource.lpProvider = null; int result = WNetAddConnection2(resource, App.Password, App.Username, CONNECT_TEMPORARY); if (result == NO_ERROR) { Log.WriteInformation(string.Format("CONNECTION to share {0} SUCCEEDED", currentPathRoot)); } else { Log.WriteError(string.Format("CONNECTION to share {0} FAILED", currentPathRoot)); Log.WriteException(new Win32Exception(Marshal.GetLastWin32Error())); } } WIN32_FIND_DATA wfd; //IntPtr hFile = FindFirstFile(Path.Combine(currentPathRoot,"*"),out wfd); IntPtr hFile = FindFirstFileEx(Path.Combine(currentPathRoot, extension), FINDEX_INFO_LEVELS.FindExInfoStandard, out wfd, FINDEX_SEARCH_OPS.FindExSearchLimitToDirectories, IntPtr.Zero, 0); if (hFile != INVALID_HANDLE_VALUE) { if ((wfd.dwFileAttributes & 0x10) == 0 && wfd.cFileName != "." && wfd.cFileName != "..") { Log.WriteInformation(string.Format("FOUND file {0} under {1}", wfd.cFileName, currentPathRoot)); filesFound.Add(wfd.cFileName); } while (FindNextFile(hFile, out wfd)) { if ((wfd.dwFileAttributes & 0x10) == 0 && wfd.cFileName != "." && wfd.cFileName != "..") { Log.WriteInformation(string.Format("FOUND file {0} under {1}", wfd.cFileName, currentPathRoot)); filesFound.Add(wfd.cFileName); } } FindClose(hFile); } else { throw new Win32Exception(Marshal.GetLastWin32Error()); } } }// foreach ext return(filesFound.ToArray()); }
public string[] LoadDirectories(string currentPathRoot) { List <string> directoriesFound = new List <string>(); try { directoriesFound = Directory.GetDirectories(currentPathRoot).ToList(); directoriesFound = directoriesFound.Where(f => { return(f != "." && f != ".."); }).ToList(); foreach (string dir in directoriesFound) { Log.WriteInformation(string.Format("FOUND directory {0}", dir)); } } catch (Exception) { if (currentPathRoot.StartsWith("\\\\") && !string.IsNullOrEmpty(App.Username)) { Log.WriteInformation("Trying to connect to: " + currentPathRoot); NetResource resource = new NetResource(); resource.dwType = ResourceType.RESOURCETYPE_DISK; resource.lpLocalName = null; resource.lpRemoteName = currentPathRoot; resource.lpProvider = null; int result = WNetAddConnection2(resource, App.Password, App.Username, CONNECT_TEMPORARY); if (result == NO_ERROR) { Log.WriteInformation(string.Format("CONNECTION to share {0} SUCCEEDED", currentPathRoot)); } else { Log.WriteError(string.Format("CONNECTION to share {0} FAILED", currentPathRoot)); Log.WriteException(new Win32Exception(Marshal.GetLastWin32Error())); } } WIN32_FIND_DATA wfd; //IntPtr hFile = FindFirstFile(Path.Combine(currentPathRoot,"*"),out wfd); IntPtr hFile = FindFirstFileEx(Path.Combine(currentPathRoot, "*"), FINDEX_INFO_LEVELS.FindExInfoStandard, out wfd, FINDEX_SEARCH_OPS.FindExSearchLimitToDirectories, IntPtr.Zero, 0); if (hFile != INVALID_HANDLE_VALUE) { if ((wfd.dwFileAttributes & 0x10) > 0 && wfd.cFileName != "." && wfd.cFileName != "..") { Log.WriteInformation(string.Format("FOUND directory {0}", wfd.cFileName)); directoriesFound.Add(wfd.cFileName); } while (FindNextFile(hFile, out wfd)) { if ((wfd.dwFileAttributes & 0x10) > 0 && wfd.cFileName != "." && wfd.cFileName != "..") { Log.WriteInformation(string.Format("FOUND directory {0}", wfd.cFileName)); directoriesFound.Add(wfd.cFileName); } } FindClose(hFile); } else { throw new Win32Exception(Marshal.GetLastWin32Error()); } } return(directoriesFound.ToArray()); }
public NetworkConnection(string networkName, NetworkCredential credentials, bool timeout) { _networkName = networkName; var netResource = new NetResource() { Scope = ResourceScope.GlobalNetwork, ResourceType = ResourceType.Disk, DisplayType = ResourceDisplaytype.Share, RemoteName = networkName }; try { var result = 0; if (timeout == true) { var tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; int timeOut = MainWindow.TIMEOUT; var task = Task.Factory.StartNew(() => { result = WNetAddConnection2( netResource, credentials.Password, credentials.UserName, 0); }, token); if (!task.Wait(timeOut, token)) throw new Win32Exception("The request timed out."); } else { result = WNetAddConnection2( netResource, credentials.Password, credentials.UserName, 0); } if (result != 0) { throw new Win32Exception(result); } } catch (Exception ex) { throw new Exception("Error connecting to remote share: " + ex.Message); } }
internal static extern int WNetAddConnection2(ref NetResource lpNetResource, string lpPassword, string lpUsername, ConnectionOptions dwFlags);
private static extern int WNetAddConnection2A(ref NetResource refNetResource, string inPassword, string inUsername, int inFlags);
internal static extern int WNetAddConnection2(ref NetResource netResource, byte[] password, string username, int flags);
private static extern int WNetAddConnection2( NetResource netResource, string password, string username, ZlpNetworkConnectionFlags flags);
private void DoWorkConnect(object sender, DoWorkEventArgs eventArgs) { try { IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(Ip), Port); uclient = new UdpClient(); uclient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); uclient.DontFragment = true; uclient.Connect(ipep); tcpclnt = new TcpClient(); Console.WriteLine("Connecting....."); Status = 2; tcpclnt.NoDelay = true; tcpclnt.Connect(Ip, Port); Console.WriteLine("Connected"); tcpclnt.GetStream().Write(publicKey, 0, publicKey.Length); byte[] serverPublicKey = new byte[72]; tcpclnt.GetStream().Read(serverPublicKey, 0, 72); byte[] derivedKey = exch.DeriveKeyMaterial(CngKey.Import(serverPublicKey, CngKeyBlobFormat.EccPublicBlob)); StreamWriter stream = new StreamWriter(tcpclnt.GetStream()); stream.WriteLine(Username); stream.Flush(); Aes aes = new AesCryptoServiceProvider(); aes.Key = derivedKey; byte[] bytes = new byte[aes.BlockSize / 8]; bytes.Initialize(); System.Buffer.BlockCopy(Username.ToCharArray(), 0, bytes, 0, bytes.Length > Username.Length * sizeof(char) ? Username.Length * sizeof(char) : bytes.Length); aes.IV = bytes; ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); MemoryStream ms = new MemoryStream(64); CryptoStream csEncrypt = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); byte[] passArr = Encoding.UTF8.GetBytes(Password); csEncrypt.Write(passArr, 0, passArr.Length); csEncrypt.Close(); byte[] tosend = ms.ToArray(); string encpass = Convert.ToBase64String(tosend, 0, tosend.Length); stream.WriteLine(encpass); stream.Flush(); byte[] auth = new byte[sizeof(bool)]; tcpclnt.GetStream().Read(auth, 0, sizeof(bool)); bool result = BitConverter.ToBoolean(auth, 0); eventArgs.Result = result; } catch (Exception ioe) { eventArgs.Result = false; } if ((bool)eventArgs.Result) { Action act = new Action(() => { var netResource = new NetResource() { Scope = ResourceScope.GlobalNetwork, ResourceType = ResourceType.Disk, DisplayType = ResourceDisplaytype.Share, RemoteName = "\\\\" + Ip + "\\C" }; var result = WNetAddConnection2( netResource, Password, null, 0x00000004 | 0x00000008 | 0x1000); if (result != 0) { Console.WriteLine("Result not zero: " + result); } }); Thread t = new Thread(() => act()); t.Start(); } }
private void WinMapNetworkDrive(PSDriveInfo drive) { if (drive != null && !string.IsNullOrEmpty(drive.Root)) { const int CONNECT_UPDATE_PROFILE = 0x00000001; const int CONNECT_NOPERSIST = 0x00000000; const int RESOURCE_GLOBALNET = 0x00000002; const int RESOURCETYPE_ANY = 0x00000000; const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000; const int RESOURCEUSAGE_CONNECTABLE = 0x00000001; // By default the connection is not persisted. int CONNECT_TYPE = CONNECT_NOPERSIST; string driveName = null; byte[] passwd = null; string userName = null; if (drive.Persist) { if (IsSupportedDriveForPersistence(drive)) { CONNECT_TYPE = CONNECT_UPDATE_PROFILE; driveName = drive.Name + ":"; drive.DisplayRoot = drive.Root; } else { //error. ErrorRecord er = new ErrorRecord(new InvalidOperationException(FileSystemProviderStrings.InvalidDriveName), "DriveNameNotSupportedForPersistence", ErrorCategory.InvalidOperation, drive); ThrowTerminatingError(er); } } // If alternate credentials is supplied then use them to get connected to network share. if (drive.Credential != null && !drive.Credential.Equals(PSCredential.Empty)) { userName = drive.Credential.UserName; passwd = SecureStringHelper.GetData(drive.Credential.Password); } try { NetResource resource = new NetResource(); resource.Comment = null; resource.DisplayType = RESOURCEDISPLAYTYPE_GENERIC; resource.LocalName = driveName; resource.Provider = null; resource.RemoteName = drive.Root; resource.Scope = RESOURCE_GLOBALNET; resource.Type = RESOURCETYPE_ANY; resource.Usage = RESOURCEUSAGE_CONNECTABLE; int code = NativeMethods.WNetAddConnection2(ref resource, passwd, userName, CONNECT_TYPE); if (code != 0) { ErrorRecord er = new ErrorRecord(new System.ComponentModel.Win32Exception(code), "CouldNotMapNetworkDrive", ErrorCategory.InvalidOperation, drive); ThrowTerminatingError(er); } if (CONNECT_TYPE == CONNECT_UPDATE_PROFILE) { // Update the current PSDrive to be a persisted drive. drive.IsNetworkDrive = true; // PsDrive.Root is updated to the name of the Drive for // drives targeting network path and being persisted. drive.Root = driveName + @"\"; } } finally { // Clear the password in the memory. if (passwd != null) { Array.Clear(passwd, 0, passwd.Length - 1); } } } }
public int AddConnection(NetResource netResource, string password, string username, int flags) { return(NativeMethods.WNetAddConnection2(netResource, password, username, flags)); }
public static extern int WNetAddConnection2A(ref NetResource netresource, string password, string username, int flags);
public int UseConnection(IntPtr hwndOwner, NetResource netResource, string password, string username, int flags, string lpAccessName, string lpBufferSize, string lpResult) { return(NativeMethods.WNetUseConnection(hwndOwner, netResource, password, username, flags, lpAccessName, lpBufferSize, lpResult)); }
internal static extern int WNetAddConnection2( NetResource netResource, string password, string username, int flags);
static extern UInt32 WNetAddConnection3( IntPtr hWndOwner, ref NetResource netResource, string password, string username, uint flags);
private void MapNetworkDrive(PSDriveInfo drive) { if ((drive != null) && !string.IsNullOrEmpty(drive.Root)) { int flags = 0; string str = null; byte[] password = null; string username = null; if (drive.Persist) { if (this.IsSupportedDriveForPersistence(drive)) { flags = 1; str = drive.Name + ":"; drive.DisplayRoot = drive.Root; } else { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(FileSystemProviderStrings.InvalidDriveName), "DriveNameNotSupportedForPersistence", ErrorCategory.InvalidOperation, drive); base.ThrowTerminatingError(errorRecord); } } if ((drive.Credential != null) && !drive.Credential.Equals(PSCredential.Empty)) { username = drive.Credential.UserName; password = SecureStringHelper.GetData(drive.Credential.Password); } try { NetResource netResource = new NetResource { Comment = null, DisplayType = 0, LocalName = str, Provider = null, RemoteName = drive.Root, Scope = 2, Type = 0, Usage = 1 }; int error = NativeMethods.WNetAddConnection2(ref netResource, password, username, flags); if (error != 0) { ErrorRecord record2 = new ErrorRecord(new Win32Exception(error), "CouldNotMapNetworkDrive", ErrorCategory.InvalidOperation, drive); base.ThrowTerminatingError(record2); } if (flags == 1) { drive.IsNetworkDrive = true; drive.Root = str + @"\"; } } finally { if (password != null) { Array.Clear(password, 0, password.Length - 1); } } } }
private static extern int WNetAddConnection2A(ref NetResource pstNetRes, string psPassword, string psUsername, int piFlags);
[DllImport("mpr.dll")] private static extern int WNetAddConnection2(ref NetResource lpNetResource, string lpPassword, string lpUsername, int dwFlags);
private static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flags);
public static bool MapDrive(string drive, string unc) { // CHAR szDeviceName[80]; // DWORD cchBuff = sizeof(szDeviceName); // DWORD int rc, rc2; string szDeviceName = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; int cchBuff = szDeviceName.Length; int rc, rc2; NetResource resource = new NetResource(); resource.scope = RESOURCE_CONNECTED; resource.type = RESOURCETYPE_DISK; resource.displayType = RESOURCEDISPLAYTYPE_SERVER; // Map the network drive resource.comment = null; resource.provider = null; // Check to see if this connected drive is correct if (WNetGetConnection(drive, szDeviceName, ref cchBuff) == NO_ERROR) { if (szDeviceName.ToLower() != unc.ToLower()) { string local = drive; resource.localName = local; resource.remoteName = unc; rc = WNetCancelConnection2(resource.localName, CONNECT_UPDATE_PROFILE, true); if (rc != NO_ERROR) { char[] buffer = new char[255]; char[] buffer2 = new char[255]; rc2 = WNetGetLastError( ref rc, // error code buffer, // error description buffer 255, // size of description buffer buffer2, // buffer for provider name 255 // size of provider name buffer ); } else { rc = WNetAddConnection2(ref resource, null, null, CONNECT_UPDATE_PROFILE); if (rc != NO_ERROR) { return(false); } else { return(true); } } } else { return(true); } } // Try to connect it without disconnection else { resource.localName = drive; resource.remoteName = unc; rc = WNetAddConnection2(ref resource, null, null, CONNECT_UPDATE_PROFILE); if (rc != NO_ERROR) { return(false); } else { return(true); } } return(true); }
private static extern ErrorCodes WNetOpenEnum(ResourceScope dwScope, ResourceType dwType, ResourceUsage dwUsage, NetResource p, out IntPtr lphEnum);
public bool MapDrive(string remoteName, string localName, string username, string password) { //CopyFileEx("foo", "foobar", new System.IntPtr(2), ref ss, 3); if (remoteName == null || remoteName == "") { return(false); } if (localName == null || localName == "") { return(false); } NetResource nr = new NetResource(); nr.type = RESOURCETYPE_DISK; nr.localName = localName; nr.remoteName = remoteName; nr.provider = null; // unused by WNetAddConnection2A() nr.scope = 0; nr.displayType = 0; nr.usage = 0; nr.comment = ""; // set the flags int flags = 0; if (this.interactive) { flags |= CONNECT_INTERACTIVE; } if (this.prompt) { flags |= CONNECT_PROMPT; } if (this.persistent) { flags |= CONNECT_UPDATE_PROFILE; } if (this.saveCredentials) { flags |= CONNECT_CMD_SAVECRED; } if (this.force) { flags |= CONNECT_REDIRECT; } if (this.useCommandLine) { flags |= CONNECT_COMMANDLINE; } if (WNetAddConnection2A(ref nr, password, username, flags) > 0) { //MessageBox.Show("WNetAddConnection2A() failed"); //throw new Exception("Couldn't map network drive"); return(false); } return(true); }
public ServerEnum(ResourceScope scope, ResourceType type, ResourceUsage usage, ResourceDisplayType displayType, string kPath) { var netRoot = new NetResource(); EnumerateServers(netRoot, scope, type, usage, displayType, kPath); }
// import unmanaged functions [DllImport("mpr.dll")] private static extern int WNetAddConnection2A(ref NetResource pstNetRes, string psPassword, string psUsername, int piFlags);
public ConnectToSharedFolder(Computer computer, string networkName, NetworkCredential credentials, bool Kerberos) { _networkName = networkName; string protocol = "Kerberos"; if (!Kerberos) { protocol = "NTLM"; } DateTime dtime; var netResource = new NetResource { Scope = ResourceScope.GlobalNetwork, ResourceType = ResourceType.Disk, DisplayType = ResourceDisplaytype.Share, RemoteName = networkName, }; var userName = string.IsNullOrEmpty(credentials.Domain) ? credentials.UserName : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName); var result = WNetAddConnection2(netResource, credentials.Password, userName, 0); switch (result.ToString()) { case ("0"): dtime = DateTime.Now; Console.WriteLine("{0}[{1}] Successfully authenticated as {2} against {3} ({4})", "".PadLeft(4), dtime.ToString("MM/dd/yyyy HH:mm:ss"), userName, computer.ComputerName, protocol); break; /* * case ("1323"): * //Console.WriteLine($"The password is incorrect on {networkName}s"); * break; * * case ("1326"): * //Console.WriteLine($"The user name or password is incorrect on {networkName}"); * break; * * case ("1328"): * //Console.WriteLine($"Invalid logon hours on {networkName}"); * break; * * case ("1330"): * //Console.WriteLine($"Password expired on {networkName}"); * break; * */ default: //Console.WriteLine("Unknown Error Code on" + result.ToString()); dtime = DateTime.Now; Console.WriteLine("{0}[{1}] Failed to authenticate as {2} against {3} ({4}). Error Code:{5}", "".PadLeft(4), dtime.ToString("MM/dd/yyyy HH:mm:ss"), userName, computer.ComputerName, protocol, result.ToString()); break; } //Console.WriteLine("WNetAddConnection2 returned " + result.ToString()); /* * if (result != 0) * { * //throw new Win32Exception(result, "Error connecting to remote share"); * //throw; * }*/ }
public int AddConnection(NetResource netResource, string password, string username, int flags) { return NativeMethods }