Log in using a domain account to access the network path
1 Public classfiletool:idisposable2 {3[DllImport ("Kernel32.dll", CharSet =CharSet.Auto)]4 Private Static extern BOOLCloseHandle (IntPtr handle);5[DllImport ("Advapi32.dll", CharSet = CharSet.Auto, SetLastError =true)]6 Private Static extern intDuplicateToken (IntPtr Htoken,intImpersonationLevel,refIntPtr hNewToken);7[DllImport ("Advapi32.dll", SetLastError =true)]8 Private Static extern intLogonUser (stringlpszUserName,stringLpszdomain,stringLpszpassword,intdwLogonType,intdwLogonProvider,refIntPtr phtoken);9[DllImport ("Advapi32.dll", CharSet = CharSet.Auto, SetLastError =true)]Ten Private Static extern BOOLRevertToSelf (); One A Private Const intLogon32_logon_interactive =2; - Private Const intLogon32_provider_default =0; - PrivateWindowsImpersonationContext impersonationcontext; the PrivateIntPtr _oldtokenhandle =IntPtr.Zero; - - /// <summary> - ///switching users via the win API + /// </summary> - /// <param name= "Oldtokenhandle" >Oldtokenhandle</param> + /// <param name= "UserName" >User name</param> A /// <param name= "domain" >Domain name</param> at /// <param name= "password" >Password</param> - PublicFiletool (IntPtr Oldtokenhandle,stringUserName,stringDomainstringpassword) - { -WindowsIdentity tempwindowsidentity =NULL; -INTPTR token =IntPtr.Zero; -IntPtr tokenduplicate =IntPtr.Zero; in_oldtokenhandle =Oldtokenhandle; - to Try + { - if(RevertToSelf ()) the { * if(LogonUser (userName, domain, password, $ Logon32_logon_interactive,Panax Notoginseng Logon32_provider_default, - reftoken)! =0) the { + if(DuplicateToken (token,2,reftokenduplicate)! =0) A { thetempWindowsIdentity =NewWindowsIdentity (tokenduplicate); +impersonationcontext =tempwindowsidentity.impersonate (); - } $ Else $ { - } - } the Else - {Wuyi } the } - Else Wu { - } About } $ finally - { - if(Token! =IntPtr.Zero) - { A CloseHandle (token); + } the if(Tokenduplicate! =IntPtr.Zero) - { $ CloseHandle (tokenduplicate); the } the } the } the - /// <summary> in ///Switch back to the original user the /// </summary> the Public voidundoimpersonation () About { the if(Impersonationcontext! =NULL) the { the Impersonationcontext.undo (); +WindowsIdentity tempwindowsidentity =NewWindowsIdentity (_oldtokenhandle); - tempwindowsidentity.impersonate (); the }Bayi } the the /// <summary> - ///Release - /// </summary> the Public voidDispose () the { the undoimpersonation (); the } -}
Call
1 Public Staticfiletool Dofiletool ()2 {3 return NewFiletool (WindowsIdentity.GetCurrent (). Token,"username","Domain","Password");4 }5 6 Private voidForm1_Load (Objectsender, EventArgs e)7 {8 using(Filetool pp =Dofiletool ())9 {Ten Try One { AFile.Copy (@"C:\Users\AAA\Desktop\Alice\DLEQ_Import.7z",@"\\SZXXX\TEST20170630\DLEQ_Import.7z",true); - } - Catch(Exception ex) the { - MessageBox.Show (ex. Message); - } - } +}
C # Log in with a domain account to access the network path