定义类:
1 public class ShareFolderHelper : IDisposable 2 { 3 //Obtains user token 4 [DllImport("advapi32.dll", SetLastError = true)] 5 static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); 6 7 //Close open handes returned by LogonUser 8 [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 9 extern static bool CloseHandle(IntPtr handle); 10 11 [DllImport("Advapi32.DLL")] 12 static extern bool ImpersonateLoggedOnUser(IntPtr hToken); 13 14 [DllImport("Advapi32.DLL")] 15 static extern bool RevertToSelf(); 16 const int LOGON32_PROVIDER_DEFAULT = 0; 17 const int LOGON32_LOGON_NEWCREDENTIALS = 9;//域控中的需要用:Interactive = 2 18 private bool disposed; 19 20 public ShareFolderHelper(string Username, string Password, string IP) 21 { 22 // initialize tokens 23 IntPtr pExistingTokenHandle = new IntPtr(0); 24 IntPtr pDuplicateTokenHandle = new IntPtr(0); 25 26 try 27 { 28 // get handle to token 29 bool bImpersonated = LogonUser(Username, IP, Password, LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle); 30 31 if (bImpersonated) 32 { 33 if (!ImpersonateLoggedOnUser(pExistingTokenHandle)) 34 { 35 int nErrorCode = Marshal.GetLastWin32Error(); 36 throw new Exception("ImpersonateLoggedOnUser error;Code=" + nErrorCode); 37 } 38 } 39 else 40 { 41 int nErrorCode = Marshal.GetLastWin32Error(); 42 throw new Exception("LogonUser error;Code=" + nErrorCode); 43 } 44 } 45 finally 46 { 47 // close handle(s) 48 if (pExistingTokenHandle != IntPtr.Zero) 49 { 50 CloseHandle(pExistingTokenHandle); 51 } 52 53 if (pDuplicateTokenHandle != IntPtr.Zero) 54 { 55 CloseHandle(pDuplicateTokenHandle); 56 } 57 } 58 } 59 60 protected virtual void Dispose(bool disposing) 61 { 62 if (!disposed) 63 { 64 RevertToSelf(); 65 disposed = true; 66 } 67 } 68 69 public void Dispose() 70 { 71 Dispose(true); 72 } 73 }
实例:
1 using (ShareFolderHelper helper = new ShareFolderHelper(connector.SF_USER_ACCOUNT, connector.SF_USER_PASSWORD, connector.SF_IP)) 2 { 3 string Path = connector.SF_PATH; 4 5 var dicInfo = new DirectoryInfo(Path);//选择的目录信息 6 7 //得到文件夹列表 8 DirectoryInfo[] folderList = dicInfo.GetDirectories("*.*", SearchOption.TopDirectoryOnly); 9 //得到文件列表 10 FileInfo[] fileList = dicInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly);//获取所有目录包含子目录下的文件 11 12 if (folderList.Length > 0 || fileList.Length > 0) 13 { 14 //Step1: 得到根Folder(包含创建) 15 SF_FOLDER rootArasFolder = GetArasRootFolder(connector); 16 17 //Step2: 同步文件 18 SyncFileToAras(connector, rootArasFolder, fileList); 19 20 //Step3: 同步子文件夹 21 SyncFolderToAras(connector, rootArasFolder, folderList); 22 } 23 else 24 { 25 MethodHelper.RecordLog("No folder or file in connector [" + connector.SF_NAME + "] [" + DateTime.Now + "]"); 26 } 27 }
【原文出处】 http://www.51aras.com/?id=12