copy files with authentication in c#

前端 未结 4 1967
礼貌的吻别
礼貌的吻别 2020-12-01 09:03

I am trying to copy file from local drive to one of folder on server. name of the folder on server is \'DBFiles\'. No one has got access to this apart from username \'user\'

4条回答
  •  暖寄归人
    2020-12-01 09:13

    You can use impersonation to change the threads user context:

    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
        int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
    ...
    LogonUser(userName, domainName, password,
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                out safeTokenHandle);
    ...
    using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                {
                    using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                    {
    
                        // Check the identity.
                        Console.WriteLine("After impersonation: "
                            + WindowsIdentity.GetCurrent().Name);
                        //Do your coping here
                    }
                }
    

    MSDN Sample windowsimpersonationcontext

提交回复
热议问题