access a directory in a domain by username and password

I have developed an application in c# using visual studio 2015, that copies some files from one directory (source) to another (destination) in general. My problem is that the source path is another computer in a domain. I wish to be able to access the directory and get my files, user the domain, username and password the source computer. I have seen some solution, but I can't get how they access the other computer. I used to get my files by using the Directory. GetDirectories (path), and I'm far too deep using it now and can't change it to smooth as. thanks for helping me with my problem I'm truly blocked for days now.

string[] folder1;
string[] folder2;
folder1 = Directory.GetDirectories(path);
foreach (string fld1 in folder1)
{
    folder2 = Directory.GetDirectories(fld);
    foreach(string fld2 in folder2)
    {
        for(int i = 0; i < MyList.Count(); i++)
        {
            if(fld2.Contains("nok") || fld2.Contains("Nok"))
                LNok = Directory.GetFiles(fld2, picList[i]);
            else
                Lok = Directory.GetFiles(fld2, picList[i]);
        }
    }
}

Since System.IO.File and System.IO.Directory methods don't support passing credentials, the preferred solution is to impersonate an authorized user account. This requires to import two methods from the advapi32.dll and kernel32.dll using pInvoke:

//Impersonation functionality
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

//Disconnection after file operations
[DllImport("kernel32.dll")]
private static extern Boolean CloseHandle(IntPtr hObject);

The following code makes use of those methods to create a WindowsImpersonationContext

const int LOGON_TYPE_NEW_CREDENTIALS = 9;
const int LOGON32_PROVIDER_WINNT50 = 3;

//User token that represents the authorized user account
IntPtr token = IntPtr.Zero;

bool result = LogonUser("username", "domainname", "password",  LOGON_TYPE_NEW_CREDENTIALS , LOGON32_PROVIDER_WINNT50, ref token);

if (result == true)
{
    //Use token to setup a WindowsImpersonationContext 
    using (WindowsImpersonationContext ctx = new WindowsIdentity(token).Impersonate())
    {
        //Your file operations
        string[] files = Directory.GetFiles(@"remotemachinesharefolder");

        //Release the context, and close user token
        ctx.Undo();
        CloseHandle(token);
    }
}

Here you may find the MSDN documentation of the LogonUser function

链接地址: http://www.djcxy.com/p/6130.html

上一篇: 使用NSFetchedResultsController自定义部分?

下一篇: 通过用户名和密码访问域中的目录