Copy files between servers in different(without) domains

By | April 15, 2011

It’s quite tough there days because of the file uploading failure on our live servers. The situation is that we have the Application Server and DB server(which also used as file server) in two different domains(in fact, both servers are not in domain).

At first, we use the following code to save files to another server:

file.SaveAs(newFilePath);

The code is ok if two servers are in same domain. But it fails in the situation describe above. We cannot change the environment, so we can just do an impersonation to logon the file server first, then copy the files, we updated the code:

The definition:

#region consts

const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
const int LOGON32_PROVIDER_DEFAULT = 0;

#endregion

#region Windowns API

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

#endregion

Copy file code:

//do the impersonation to save the file
IntPtr admin_token = default(IntPtr);
WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
WindowsIdentity wid_admin = null;
WindowsImpersonationContext wic = null;
string domain = "your_domain_or_target_server_name";
string userName = "target_server_local_user_name";
string password = "target_server_local_user_password";


try
{
    if (LogonUser(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref admin_token) != 0)
    {
        wid_admin = new WindowsIdentity(admin_token);
        wic = wid_admin.Impersonate();

        //write the file
        file.SaveAs(newFilePath);
    }
}
catch (System.Exception se)
{
    int ret = Marshal.GetLastWin32Error();
    throw;
}
finally
{
    if (wic != null)
    {
        wic.Undo();
    }
}

Then it should work.Smile