代码加注释:
01 | using System; |
02 | using System.Collections.Generic; |
03 | using System.Linq; |
04 | using System.Text; |
05 | using System.Security.Principal; |
06 | using System.Runtime.InteropServices; |
07 | using System.IO; |
08 | |
09 | namespace ConsoleApplication3 |
10 | { |
11 | internal static class WinLogonHelper |
12 | { |
13 | /// <summary> |
14 | /// 模拟windows登录域 |
16 | /// </summary> |
17 | [DllImport( "advapi32.DLL" , SetLastError = true )] |
18 | public static extern int LogonUser( string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); |
19 | } |
20 | |
21 | class Program |
22 | { |
23 | static void Main( string [] args) |
24 | { |
25 | IntPtr admin_token = default (IntPtr); |
26 | WindowsIdentity wid_admin = null ; |
27 | WindowsImpersonationContext wic = null ; |
28 | |
29 | //在程序中模拟域帐户登录 |
30 | if (WinLogonHelper.LogonUser( "uid" , "serverdomain" , "pwd" , 9, 0, ref admin_token) != 0) |
31 | { |
32 | using (wid_admin = new WindowsIdentity(admin_token)) |
33 | { |
34 | using (wic = wid_admin.Impersonate()) |
35 | { |
36 | //假定要操作的文件路径是10.0.250.11上的d:/txt.txt文件可以这样操作 |
37 | FileInfo file = new FileInfo( @"//10.0.250.11/d$/txt.txt" ); |
38 | //想做什么操作就可以做了 |
39 | } |
40 | } |
41 | } |
42 | } |
43 | } |
44 | } |
模拟域帐户之后,就有了模拟用户的权限,这里千万要注意安全!