Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过用户名和密码访问域中的目录_C#_Getdirectories - Fatal编程技术网

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

C# 通过用户名和密码访问域中的目录,c#,getdirectories,C#,Getdirectories,我使用visual studio 2015在c#中开发了一个应用程序,它通常将一些文件从一个目录(源)复制到另一个目录(目标)。 我的问题是源路径是域中的另一台计算机。我希望能够访问目录,并获得我的文件,用户域,用户名和密码的源计算机。 我看到了一些解决方案,但我不知道他们如何访问另一台计算机。 我过去经常使用目录获取文件。GetDirectory(路径),我现在使用它太深了,无法将其更改为平滑。 谢谢你帮我解决我的问题,我真的被困了好几天了 string[]folder1; 字符串[]fol

我使用visual studio 2015在c#中开发了一个应用程序,它通常将一些文件从一个目录(源)复制到另一个目录(目标)。 我的问题是源路径是域中的另一台计算机。我希望能够访问目录,并获得我的文件,用户域,用户名和密码的源计算机。 我看到了一些解决方案,但我不知道他们如何访问另一台计算机。 我过去经常使用目录获取文件。GetDirectory(路径),我现在使用它太深了,无法将其更改为平滑。 谢谢你帮我解决我的问题,我真的被困了好几天了

string[]folder1;
字符串[]folder2;
folder1=Directory.GetDirectories(路径);
foreach(folder1中的字符串fld1)
{
folder2=Directory.GetDirectories(fld);
foreach(folder2中的字符串fld2)
{
对于(int i=0;i}
由于
System.IO.File
System.IO.Directory
方法不支持传递凭据,因此首选的解决方案是模拟授权用户帐户。这需要使用pInvoke从advapi32.dll和kernel32.dll导入两个方法:

//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);
下面的代码使用这些方法创建
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(@"\\remotemachine\share\folder");

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

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

请向我们展示您迄今为止尝试的代码以及错误发生的位置。这就是我获取文件的方式,并且它与此链接在我的应用程序中的每个位置,它都工作得很好,直到我必须从域中的计算机获取文件,并使用用户名和密码锁定。您好,我确实尝试过你的建议,在运行模式下没有异常,但我没有得到任何结果,没有加载任何文件。就像我查找的目录是空的一样&我确定它不是空的。我在stackoverflow上搜索了类似的帖子,找到了。看看投票最多的答案,建议在LogonUser函数上使用不同的参数<代码>const int LOGON\u TYPE\u NEW\u凭证=9;const int LOGON32\u PROVIDER\u WINNT50=3;bool returnValue=LogonUser(用户、域、密码、登录类型、新凭据、LOGON32、提供者、ref令牌)我已经在与backgroundworker合作,我担心如果我实现您提到的示例,我会遇到冲突我指的是takrl的答案,没有backgroundworker,只是关于LogonUser参数的建议。