如何在c#程序中模拟域帐户进行登录操作

来源:互联网 发布:steam屏保软件 编辑:程序博客网 时间:2024/06/07 12:37

代码加注释:

view source
print?
01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Text;
05using System.Security.Principal;
06using System.Runtime.InteropServices;
07using System.IO;
08  
09namespace ConsoleApplication3
10{
11    internal static class WinLogonHelper
12    {
13        /// <summary>
14        /// 模拟windows登录域
15        ///http://www.cnblogs.com/yukaizhao/
16        /// </summary>
17        [DllImport("advapi32.DLL", SetLastError = true)]
18        public static extern int LogonUser(string lpszUsername,stringlpszDomain,string lpszPassword,int dwLogonType,int dwLogonProvider,refIntPtr 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, refadmin_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}

模拟域帐户之后,就有了模拟用户的权限,这里千万要注意安全!

原创粉丝点击