在C#中将SID转换为GUID?

时间:2018-08-30 12:02:24

标签: c# .net

我想从广告活动目录和组中的给定Sid值中获取GUID值。

class Program
{
    static string myGuid;
    static void Main(string[] args)
    {
        myGuid = GetGuidString("S-1-5-21-1520874019-1059933425-2350978085-6519");

        Console.WriteLine(myGuid);
        Console.ReadKey();
    }
    public static string GetGuidString(string sid)
    {
        return Guid.Parse(sid).ToString();
    }   
}

1 个答案:

答案 0 :(得分:0)

您需要查询活动目录。这是一个vb解决方案,您可以翻译它,也可以只查看System.DirectoryServices命名空间。

'example sid: S-1-5-21-2407707581-4260124077-1944392116-13936
Function getGuidFromSid(ByVal sid As String) As String
    Dim rootEntry As New DirectoryServices.DirectoryEntry()
    Dim searcher As New DirectoryServices.DirectorySearcher(rootEntry)
    searcher.PropertiesToLoad.AddRange(New String() {"sAMAccountName", "objectGUID"})
    searcher.Filter = "(&(objectSid=" & sid & ")(objectCategory=person))"
    Dim results As DirectoryServices.SearchResultCollection
    results = searcher.FindAll()
    Dim ret = results.Item(0).Properties("objectGUID").Item(0) 'quick and dirty, please handle nulls etc
    Return ret
End Function