访问网络驱动器上的文件

Dav*_*jak 12 c# network-drive

背景:我有一个应用程序必须从网络驱动器上的文件读取(Z :)

这在我的办公室域中很有用,但它不能在站点上工作(在不同的域中).据我所知,域用户和网络驱动器的设置方式相同,但我无法访问客户域中的用户等.

当我无法访问网络驱动器时,我想我需要一个用户令牌.这就是我对用户进行压制的方式:

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
Run Code Online (Sandbox Code Playgroud)

...

const string userName = "USER";
const string pass = "PASS";
const string domainName = "VALIDDOMAIN.local"  //tried with valid domain name and with null, same result
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;

IntPtr tokenHandle = new IntPtr(0);

bool returnValue = LogonUser(userName, domainName, pass,
            LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
            ref tokenHandle);

if (!returnValue)
    throw new Exception("Logon failed.");

WindowsImpersonationContext impersonatedUser = null;
try
{
    WindowsIdentity wid = new WindowsIdentity(tokenHandle);
    impersonatedUser = wid.Impersonate();

}
finally
{
    if (impersonatedUser != null) impersonatedUser.Undo();
}
Run Code Online (Sandbox Code Playgroud)

现在这里是有趣/奇怪的部分.在我的网络中,应用程序已经可以访问网络驱动器,如果我尝试模拟活动用户(完全相同的用户,包括相同的域),它将无法访问网络驱动器.

这使我无助,因为现在我不知道什么有效,什么不可用,更重要的是,它会在现场工作吗?

我错过了什么?

编辑:我最初在问这个问题时忘记写这个:我尝试输入一个有效的域名但它没有用,所以在那之后我尝试输入null来获得与没有这个代码时相同的用户名(因为它有效)默认情况下在我们的域中).这没有用,这就是domain = null; 结束了这个问题.

Kei*_*ler 7

一些想法:

  • 不要使用逻辑驱动器路径从代码访问网络资源.始终使用UNC路径(例如\\SERVER\Share\Filename.ext).
  • 启用从本地安全策略审核登录/注销事件,以便在调用Impersonate方法时,可以非常详细地跟踪故障/成功
  • 您最好在自己的域中创建一个帐户,该帐户的用户名和密码与另一个域中的帐户相同.通过身份验证您的域和传递身份验证将允许您访问其他域上的网络共享.