2009-02-16 [.NET C#] 模擬角色遠端新增資料夾 4105 0 .Net C# 2009-04-16 摘要:[.NET C#] 模擬角色遠端新增資料夾 之前在幫公司寫專案時剛好有寫到這樣的功能因為公司內存在多個網域而需要對各網域做資料夾的新增時所用到的程式碼分享如下:using System; using System.IO; using System.Security.Principal; using System.Runtime.InteropServices; /// <summary> /// Summary description for Class1 /// </summary> public class Class1 { public const int LOGON32_LOGON_INTERACTIVE = 2; public const int LOGON32_PROVIDER_DEFAULT = 0; public static WindowsImpersonationContext impersonationContext; [DllImport("advapi32.dll")] public static extern int LogonUserA(String lpszUserName, String lpszDomain, 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); private static bool impersonateValidUser(String userName, String domain, String password) { WindowsIdentity tempWindowsIdentity; IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; if (RevertToSelf()) { if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0) { if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); WindowsImpersonationContext impersonationContext = tempWindowsIdentity.Impersonate(); if (impersonationContext != null) { CloseHandle(token); CloseHandle(tokenDuplicate); return true; } } } } if (token != IntPtr.Zero) { CloseHandle(token); } if (tokenDuplicate != IntPtr.Zero) { CloseHandle(tokenDuplicate); } return false; } //建立資料夾 public static void CreateDocumentFolder(string strFolderPath) { //判斷path為 c:\folder(本機) or \\210.12.41.11\folder(外主機) int partFiles = strFolderPath.IndexOf("\\\\"); if (partFiles > -1) { //代入對方主機所開設的帳號、網域、密碼 if (impersonateValidUser(strUsername, strDomain, strPassword)) { string curpath = string.Empty; string[] paths = strFolderPath.Split('\\'); curpath = "\\\\" + paths[2]; for (int j = 3; j < paths.Length; j++) { curpath = curpath + '\\' + paths[j]; if (!Directory.Exists(@"" + strFolder + "")) { Directory.CreateDirectory(@"" + strFolder + ""); } } } } else { string curpath = string.Empty; string[] paths = strFolderPath.Split('\\'); curpath = paths[0]; for (int j = 1; j < paths.Length; j++) { curpath = curpath + '\\' + paths[j]; if (!Directory.Exists(@"" + strFolder + "")) { Directory.CreateDirectory(@"" + strFolder + ""); } } } } } ASP.NETC# 回首頁