指定したファイルの所有者を取得します。
GetFileSecurity()関数にOWNER_SECURITY_INFORMATIONを渡して、 SECURITY_DESCRIPTORを取得し、 GetSecurityDescriptorOwner()関数により所有者のSIDを取得します。 所有者のSIDを文字列へ変換するには、LookupAccountSid()関数を 使用します。
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <windows.h>
#include <aclapi.h>
/*
指定したファイルのACLを取得する
*ppAclはNULL以外の場合はfree()で解放してください。
*/
HRESULT GetFileOwner
(
std::wstring oFilePath
)
{
HRESULT hResult;
ACL* pResultAcl = NULL;
BOOL bRet;
DWORD dwSecurityDescriptorSize = 0;
// SECURITY_DESCRIPTORサイズの取得
bRet = GetFileSecurity(
oFilePath.c_str()
, OWNER_SECURITY_INFORMATION // オーナー情報を取得
, NULL
, 0
, &dwSecurityDescriptorSize
);
if ( 0 == bRet ) {
DWORD dwResult = ::GetLastError();
// バッファサイズ不足以外はエラー
if ( dwResult != ERROR_INSUFFICIENT_BUFFER ) {
// エラー
return( HRESULT_FROM_WIN32( dwResult ) );
}
}
// SECURITY_DESCRIPTOR用メモリの確保
SECURITY_DESCRIPTOR* pSecurityDescriptor =
(SECURITY_DESCRIPTOR*)calloc( 1, dwSecurityDescriptorSize + 1000 );
if ( NULL == pSecurityDescriptor ) {
// メモリ不足
return( E_OUTOFMEMORY );
}
// SECURITY_DESCRIPTORの取得
bRet = GetFileSecurity(
oFilePath.c_str()
, OWNER_SECURITY_INFORMATION // オーナー情報を取得
, pSecurityDescriptor
, dwSecurityDescriptorSize
, &dwSecurityDescriptorSize
);
if ( 0 == bRet ) {
// エラー
hResult = HRESULT_FROM_WIN32( ::GetLastError() );
goto err;
}
PSID pOwnerSid;
BOOL bOwnerDefaulted;
// セキュリティ記述子から所有者情報を取得する
bRet = ::GetSecurityDescriptorOwner(
pSecurityDescriptor
, &pOwnerSid
, &bOwnerDefaulted
);
if ( 0 == bRet ) {
// エラー
hResult = HRESULT_FROM_WIN32( ::GetLastError() );
goto err;
}
/*
SIDを名前に変換して表示
*/
{
TCHAR wpAccountName[ 1024 ]; // 所有者
TCHAR wpDomainName[ 1024 ]; // ドメイン
DWORD dwAccountNameSize = 1024; // 所有者文字列のサイズ
DWORD dwDomainNameSize = 1024; // ドメイン文字列のサイズ
SID_NAME_USE nSidNameUse;
// SIDを名前に変換
LookupAccountSid(
NULL
, pOwnerSid
, wpAccountName
, &dwAccountNameSize
, wpDomainName
, &dwDomainNameSize
, &nSidNameUse
);
// SIDタイプ
const TCHAR* wpaSidType[] = {
L"SidTypeUser"
, L"SidTypeGroup"
, L"SidTypeDomain"
, L"SidTypeAlias"
, L"SidTypeWellKnownGroup"
, L"SidTypeDeletedAccount"
, L"SidTypeInvalid"
, L"SidTypeUnknown"
, L"SidTypeComputer"
, L"SidTypeLabel"
};
wprintf( L"所有者 : %s¥n", wpAccountName );
wprintf( L"ドメイン : %s¥n", wpDomainName );
wprintf( L"SIDタイプ: %s¥n", wpaSidType[ nSidNameUse - 1 ] );
}
// 正常終了
hResult = S_OK;
err:
// SECURITY_DESCRIPTORの解放
if ( pSecurityDescriptor ) {
free( pSecurityDescriptor );
}
// 正常終了
return( hResult );
}
/*
ファイルの所有者を取得する
*/
int _tmain
(
int argc
, _TCHAR* argv[]
)
{
// 標準出力にユニコード出力する
setlocale( LC_ALL, "Japanese" );
HRESULT hResult;
// ファイルの所有者を取得する
hResult = GetFileOwner( L"c:¥¥org¥¥test1.txt" );
// 正常終了
return( 0 );
}
所有者 : MyOwner ドメイン : MyDomain SIDタイプ: SidTypeUser