通过用户名和密码访问域中的目录

Meh*_*tou 2 c# getdirectories

我使用 Visual Studio 2015 在 C# 中开发了一个应用程序,该应用程序通常将一些文件从一个目录(源)复制到另一个目录(目标)。我的问题是源路径是域中的另一台计算机。我希望能够访问该目录并获取我的文件、用户域、源计算机的用户名和密码。我已经看到了一些解决方案,但我无法了解他们如何访问另一台计算机。我曾经通过使用目录来获取我的文件。GetDirectories(路径),我现在使用它太深了,无法将其更改为平滑。感谢您帮助我解决我的问题,我现在确实被封锁了好几天。

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]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sim*_*ani 6

由于System.IO.File方法System.IO.Directorydon\xe2\x80\x99 不支持传递凭据,因此首选解决方案是模拟授权用户帐户。这需要使用 pInvoke 从 advapi32.dll 和 kernel32.dll 导入两个方法:

\n\n
//Impersonation functionality\n[DllImport("advapi32.dll", SetLastError = true)]\nprivate static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);\n\n//Disconnection after file operations\n[DllImport("kernel32.dll")]\nprivate static extern Boolean CloseHandle(IntPtr hObject);\n
Run Code Online (Sandbox Code Playgroud)\n\n

以下代码利用这些方法来创建WindowsImpersonationContext

\n\n
const int LOGON_TYPE_NEW_CREDENTIALS = 9;\nconst int LOGON32_PROVIDER_WINNT50 = 3;\n\n//User token that represents the authorized user account\nIntPtr token = IntPtr.Zero;\n\nbool result = LogonUser("username", "domainname", "password",  LOGON_TYPE_NEW_CREDENTIALS , LOGON32_PROVIDER_WINNT50, ref token);\n\nif (result == true)\n{\n    //Use token to setup a WindowsImpersonationContext \n    using (WindowsImpersonationContext ctx = new WindowsIdentity(token).Impersonate())\n    {\n        //Your file operations\n        string[] files = Directory.GetFiles(@"\\\\remotemachine\\share\\folder");\n\n        //Release the context, and close user token\n        ctx.Undo();\n        CloseHandle(token);\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

在这里您可以找到 LogonUser 函数的 MSDN 文档

\n