C# Copy files from one server to another

Sometimes we need to copy files from one sever and paste those files to another server programmatically. So for that we can use below code but we should have admin credentials of that server where we want to paste files. In below method we need to pass source path of the server, from where we want to copy and destination path of the server, where we want to paste. Also we need to provide UserName, Domain, Password of the server where we want to paste those files.


public void CopyFiles(string sourcePath, string destinationPath)
        {
            try
            { 
                IntPtr admin_token = new IntPtr();
                // use LOGON32_LOGON_NEW_CREDENTIALS as LogonType
                if (LogonUser("UserName", "Domain", "Password", 9, 0, ref admin_token) != 0)
                {
                    WindowsIdentity wid_admin = new WindowsIdentity(admin_token);
                    WindowsImpersonationContext wic = null;
                    wic = wid_admin.Impersonate();
                    System.IO.File.Copy(sourcePath + @"\E-Certificate.pdf", destinationPath + @"\E-Certificate.pdf", true);
                }
            }
            catch (Exception ex)
            {
             throw ex;
            }
        }

        [DllImport("advapi32.DLL", SetLastError = true)]
        public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);


Comments

Popular posts from this blog

Export SharePoint Online Group Users to Excel using Powershell