首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在C#中将SID转换为帐户名

如何在C#中将SID转换为帐户名
EN

Stack Overflow用户
提问于 2009-01-31 15:56:52
回答 10查看 74.9K关注 0票数 59

我有一个扫描目录并收集一些信息的C#应用程序。我想显示每个文件的帐户名。我可以在本地系统上执行此操作,方法是获取FileInfo对象的SID,然后执行以下操作:

代码语言:javascript
复制
string GetNameFromSID( SecurityIdentifier sid )
{
    NTAccount ntAccount = (NTAccount)sid.Translate( typeof( NTAccount ) );
    return ntAccount.ToString();
}

但是,这不适用于网络上的文件,可能是因为Translate()函数仅适用于本地用户帐户。我想也许我可以在SID上进行LDAP查找,所以我尝试了以下方法:

代码语言:javascript
复制
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的类,但它需要一个域名,而我也不知道如何获取它--我所拥有的只是我正在扫描的目录的路径。

提前谢谢。

EN

回答 10

Stack Overflow用户

回答已采纳

发布于 2009-02-01 23:24:29

SecurityReference对象的Translate方法在非本地SID上有效,但仅适用于域帐户。对于另一台计算机或非域设置中的本地帐户,您需要PInvoke函数LookupAccountSid,指定需要在其上执行查找的特定计算机名。

票数 19
EN

Stack Overflow用户

发布于 2009-03-11 23:37:00

在这里可以找到一个很好的答案:

The best way to resolve display username by SID?

它的要点是这样的:

代码语言:javascript
复制
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。

票数 50
EN

Stack Overflow用户

发布于 2012-07-20 07:42:11

System.DirectoryServices.AccountManagement.UserPrincipal类(msdn link)有一个静态函数FindByIdentity,用于将SID转换为用户对象。它应该能够在本地计算机或LDAP/Active Directory服务器上工作。我只对active directory使用过它。

下面是我在IIS中使用的一个示例:

代码语言:javascript
复制
// 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.
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/499053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档