Ho bisogno di ottenere il SID della macchina (non il SID dell'account del computer) in C#. Il computer è specificato come nome host, non è necessariamente un computer locale e può essere computer del dominio o del gruppo di lavoro. Ho utilizzato questo classe helper per richiamare LookupAccountName funzione API:get SID della macchina (incluso il controller di dominio primario)
private static class Helper
{
internal enum SID_NAME_USE
{
SidTypeUser = 1,
SidTypeGroup,
SidTypeDomain,
SidTypeAlias,
SidTypeWellKnownGroup,
SidTypeDeletedAccount,
SidTypeInvalid,
SidTypeUnknown,
SidTypeComputer
}
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool LookupAccountName(
string systemName,
string accountName,
byte[] sid,
ref int sidLen,
System.Text.StringBuilder domainName,
ref int domainNameLen,
out SID_NAME_USE peUse);
public static SecurityIdentifier LookupAccountName(
string systemName,
string accountName,
out string strDomainName,
out SID_NAME_USE accountType)
{
const int ERROR_INSUFFICIENT_BUFFER = 122;
int lSidSize = 0;
int lDomainNameSize = 0;
//First get the required buffer sizes for SID and domain name.
LookupAccountName(systemName,
accountName,
null,
ref lSidSize,
null,
ref lDomainNameSize,
out accountType);
if (Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER)
{
//Allocate the buffers with actual sizes that are required
//for SID and domain name.
byte[] sid = new byte[lSidSize];
var sbDomainName = new System.Text.StringBuilder(lDomainNameSize);
if (LookupAccountName(systemName,
accountName,
sid,
ref lSidSize,
sbDomainName,
ref lDomainNameSize,
out accountType))
{
strDomainName = sbDomainName.ToString();
return new SecurityIdentifier(sid, 0);
}
}
throw new Win32Exception();
}
}
e di utilizzarlo in questo modo:
Helper.SID_NAME_USE accountType;
string refDomain;
SecurityIdentifier sid = Helper.LookupAccountName("falcon.mydomain.local", "falcon", out refDomain, out accountType); //Domain computer
SecurityIdentifier sid = Helper.LookupAccountName("rat", "rat", out refDomain, out accountType); //Workgroup computer
Il mio unico problema è che questo non funziona se il computer è controller di dominio primario (ho bisogno per ottenere il SID di dominio in quel caso).