【IT168技术文档】
近遇到一个问题,有个跨两个domain的工程 其中一个进程需要跨域访问另外一个domain的share folder。这个进程是一个service 是以 local system 帐号运行的 所以访问不了。如果用户直接启动这个exe的话 是可以访问的。因为远程的sharefolder 已经开了 所有的共享权限。
一开始想用imperson(假装)的方法 就是让进程的某一段代码 假装用另外一个帐号运行 但是发现这样的假装只能使用本地的帐号 不能假装跨机器 远程的帐号。 所以是不行的
后来只能用win32API来 模拟net use的映射磁盘来实现:
[DllImport ("advapi32.dll")] public static extern int LogonUserEx(string lpszUserName, string lpzsDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern int DuplicateToken(IntPtr hToken, int impersonationlevel, ref IntPtr hNewToken); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool RevertToSelf(); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern bool CloseHandle(IntPtr handle); [DllImport("mpr.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern int WNetAddConnection2A(ref NETRESOURCE lpNetResource, [MarshalAs(UnmanagedType.LPStr)] string Password, [MarshalAs(UnmanagedType.LPStr)] string Username, int flag); NETRESOURCE mynetfolder = new NETRESOURCE(); mynetfolder.lpLocalName = "Z:"; string path = textBox4 .Text ; //s. mynetfolder.lpRemoteName = path; mynetfolder.dwDisplayType = 3; mynetfolder.dwScope = 2; mynetfolder.dwUsage = 1; //MessageBox.Show(path); mynetfolder.dwType = 0x1; mynetfolder.lpProvider = null; int result = MapNetworkResource(ref mynetfolder, Password .Text , UserName . Text , 0); //MessageBox.Show("the following process is started with account "+textBox2 .Text ); Process myprocess = new Process(); myprocess.StartInfo.FileName = "z:/test.exe"; myprocess.Start();