2014-03-06 91 views
0

讀取文件夾的權限如何獲得一個目錄寫權限具有以下名稱格式HOST用戶\ UerName針對特定用戶

我都試過,但它不工作

 DirectoryInfo di = new DirectoryInfo(path); 
     DirectorySecurity acl = di.GetAccessControl(); 
     AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); 
     //Go through the rules returned from the DirectorySecurity 
     foreach (AuthorizationRule rule in rules) 
     { 
      //If we find one that matches the identity we are looking for 
      if (user_name == rule.IdentityReference.Value)) //(rule.IdentityReference.ToString().Contains(NtAccountName)) 
      { 
       //Cast to a FileSystemAccessRule to check for access rights 
       if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.WriteData) > 0) 
       { 
        up.write = true; 
       } 

       if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.Read) > 0) 
       { 
        up.read = true; 
       } 


       if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.ExecuteFile) > 0) 
       { 
        up.execute = true; 
       } 

       if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.Delete) > 0) 
       { 
        up.delete = true; 
       } 

      } 
     } 
+1

請,不包括有關在問題的標題,除非它是沒有意義的使用的語言信息沒有它。標籤用於此目的。 –

回答

0

我這樣做。當然,這意味着用戶運行它有權更改的ACL

DirectoryInfo dInfo = new DirectoryInfo(dir); 
FileSystemAccessRule acl = new FileSystemAccessRule(WindowsIdentity.GetCurrent().Name, FileSystemRights.FullControl, AccessControlType.Allow); 

if (dInfo.Exists) 
{ 
    DirectorySecurity ds = dInfo.GetAccessControl(); 
    ds.AddAccessRule(acl); 
    dInfo.SetAccessControl(ds); 
} 

假冒其他用戶

[DllImport("advapi32.dll", SetLastError = true)] 
public static extern bool LogonUser(
     string lpszUsername, 
     string lpszDomain, 
     string lpszPassword, 
     int dwLogonType, 
     int dwLogonProvider, 
     out IntPtr phToken); 

int LOGON32_PROVIDER_DEFAULT = 0 
int LOGON32_LOGON_INTERACTIVE = 2 


IntPtr userToken = IntPtr.Zero; 
bool success = LogonUser(
    "Username", 
    "Domain Name", 
    "Password", 
    LOGON32_LOGON_INTERACTIVE, 
    LOGON32_PROVIDER_DEFAULT, 
    out userToken); 

if (!success) 
{ 
    throw new SecurityException("Logon user failed"); 
} 

using (WindowsIdentity.Impersonate(userToken)) 
{ 
    // do the stuff as user 
} 
+0

感謝您的回覆,但我如何使用格式HOST \ UserName將'WindowsIdentity'設置爲自定義用戶? –

+0

您將需要使用WindowsIdentity.Impersonate我將更新我的文章 – Tsukasa