我有一个扫描目录并收集一些信息的C#应用程序。我想显示每个文件的帐户名。我可以在本地系统上执行此操作,方法是获取FileInfo对象的SID,然后执行以下操作:
string GetNameFromSID( SecurityIdentifier sid )
{
NTAccount ntAccount = (NTAccount)sid.Translate( typeof( NTAccount ) );
return ntAccount.ToString();
}
但是,这不适用于网络上的文件,可能是因为Translate()函数仅适用于本地用户帐户。我想也许我可以在SID上进行LDAP查找,所以我尝试了以下方法:
string GetNameFromSID( SecurityIdentifier sid )
{
string str = "LDAP://<SID=" + sid.Value + ">";
DirectoryEntry dirEntry = new DirectoryEntry( str );
return dirEntry.Name;
}
这似乎是可行的,因为对"dirEntry.Name“的访问挂起了几秒钟,就好像它正在关闭并查询网络一样,但随后它抛出了一个System.Runtime.InteropServices.COMException
有人知道如何获得任意文件或SID的帐户名吗?我对网络或LDAP之类的东西了解不多。也许我应该使用一个名为DirectorySearcher的类,但它需要一个域名,而我也不知道如何获取它--我所拥有的只是我正在扫描的目录的路径。
提前谢谢。
发布于 2009-02-01 23:24:29
SecurityReference对象的Translate方法在非本地SID上有效,但仅适用于域帐户。对于另一台计算机或非域设置中的本地帐户,您需要PInvoke函数LookupAccountSid,指定需要在其上执行查找的特定计算机名。
发布于 2009-03-11 23:37:00
在这里可以找到一个很好的答案:
The best way to resolve display username by SID?
它的要点是这样的:
string sid="S-1-5-21-789336058-507921405-854245398-9938";
string account = new System.Security.Principal.SecurityIdentifier(sid).Translate(typeof(System.Security.Principal.NTAccount)).ToString();
这种方法适用于active directory上的非本地SID。
发布于 2012-07-20 07:42:11
System.DirectoryServices.AccountManagement.UserPrincipal
类(msdn link)有一个静态函数FindByIdentity
,用于将SID转换为用户对象。它应该能够在本地计算机或LDAP/Active Directory服务器上工作。我只对active directory使用过它。
下面是我在IIS中使用的一个示例:
// Set the search context to a specific domain in active directory
var searchContext = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "OU=SomeOU,DC=YourCompany,DC=com");
// get the currently logged in user from IIS
MembershipUser aspUser = Membership.GetUser();
// get the SID of the user (stored in the SecurityIdentifier class)
var sid = aspUser.ProviderUserKey as System.Security.Principal.SecurityIdentifier;
// get the ActiveDirectory user object using the SID (sid.Value returns the SID in string form)
var adUser = UserPrincipal.FindByIdentity(searchContext, IdentityType.Sid, sid.Value);
// do stuff to user, look up group membership, etc.
https://stackoverflow.com/questions/499053
复制相似问题