1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | using System; using System.IO; using System.Runtime.InteropServices; using System.Security.Principal; using System.Security.Permissions; [assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true )] [assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust" )] namespace ConsoleApplication1 { class Class1 { //登入 [DllImport( "advapi32.dll" , SetLastError = true )] public static extern bool LogonUser( string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); //登出 [DllImport( "kernel32.dll" )] public extern static bool CloseHandle(IntPtr hToken); public Class1() { string UserName = "username" ; string MachineName = "192.168.0.10" ; string Pw = "password" ; string IPath = @"\\" + MachineName + @"\shared" ; const int LOGON32_PROVIDER_DEFAULT = 0; const int LOGON32_LOGON_NEW_CREDENTIALS = 9; IntPtr tokenHandle = new IntPtr(0); tokenHandle = IntPtr.Zero; //將登入的Token放在tokenHandle bool returnValue = LogonUser(UserName, MachineName, Pw, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); //讓程式模擬登入的使用者 WindowsIdentity w = new WindowsIdentity(tokenHandle); w.Impersonate(); if ( false == returnValue) { //登入失敗的處理 return ; } //取得該目錄下的所有檔案名稱 DirectoryInfo dir = new DirectoryInfo(IPath); FileInfo[] inf = dir.GetFiles(); for ( int i = 0; i < inf.Length; i++) { Console.WriteLine(inf[i].Name); } } } } |
- 如果電腦存在於網域, LogonUser的第二個參數須用網域名: 12
LogonUser(UserName,
"myDomain"
, Pw,LOGON32_LOGON_NEW_CREDENTIALS,
LOGON32_PROVIDER_DEFAULT,
ref
tokenHandle);
- 相關參考網頁: http://www.thecodeproject.com/csharp/cpimpersonation1.asp
沒有留言:
張貼留言