2010-02-08 104 views
5

Windows中是否有類似於Linux的chown的API?在Windows中更改文件所有者

+0

Windows安全模型並不是真正以UNIX文件系統的文件所有權爲基礎的,所以這不是一個非常經常需要的工具。 – 2010-02-08 09:00:52

回答

3

從這裏摘自:http://www.perlmonks.org/?node_id=70562

// #includes omitted for the sake of sanity 
    HANDLE token; 
    char *filename = "somefile.txt"; 
    char *newuser = "someuser"; 
    DWORD len; 
    PSECURITY_DESCRIPTOR security = NULL; 
    PSID sidPtr = NULL; 
    int retValue = 1; 

    // Get the privileges you need 
    if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token)) { 
     SetPrivilege(token, "SeTakeOwnershipPrivilege", 1); 
     SetPrivilege(token, "SeSecurityPrivilege", 1); 
     SetPrivilege(token, "SeBackupPrivilege", 1); 
     SetPrivilege(token, "SeRestorePrivilege", 1); 
    } else retValue = 0; 

    // Create the security descriptor 
    if (retValue) { 
     GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, security, 0, &len); 
     security = (PSECURITY_DESCRIPTOR)malloc(len); 
     if (!InitializeSecurityDescriptor(security, SECURITY_DESCRIPTOR_REVISION)) 
      retValue = 0; 
    } 

    // Get the sid for the username 
    if (retValue) { 
     char domainbuf[4096]; 
     DWORD sidSize = 0; 
     DWORD bufSize = 4096; 
     SID_NAME_USE sidUse; 
     LookupAccountName(NULL, newuser, sidPtr, &sidSize, domainbuf, &bufSize, &sidUse); 
     sid = (PSID)malloc(sidSize); 
     if (!LookupAccountName(NULL, string, (PSID)sid, &sidSize, domainbuf, &bufSize, &sidUse)) 
      retValue = 0; 
     } 
    } 

    // Set the sid to be the new owner 
    if (retValue && !SetSecurityDescriptorOwner(security, sidPtr, 0)) 
     retValue = 0; 

    // Save the security descriptor 
    if (retValue) 
     retValue = SetFileSecurity(filename, OWNER_SECURITY_INFORMATION, security); 
    if (security) free(security); 
    if (sid) free(sid); 
    return retValue; 

`

+3

聖地獄,所有這些來代替一個簡單的'chown'調用! – 2010-02-08 08:44:52

+0

爲了避免混淆,您是否忽略了函數返回類型,名稱和參數? – 2010-02-08 08:51:58

1

您可能會發現cacls or icacls commands有用...他們不完全直接使用,雖然

你能提供一個更位信息你想要做什麼?