windows - Convert a username to a SID string in C#/.NET -


There is a question; There is not one for the other way around.

How do you change a username for a syd string, for example, to find out which HKEY_USERS subkey is related to a user of a given name?

I tell the podcast that Ask, and answer, here goes.

The easiest way is, on .NET 2.0 and above, this is:

  NTAccount f = new NTAccount ("user name"); Securityindifier s = (security identifier) ​​f.Translate (typef (security identifier)); String sidString = s.ToString ();  

is the hard way, that when the work will not, and .NET 1.1 also works at:

  [DllImport ( "advapi32. dll ", charset = CharSet.Auto, SetLastError = true)] public static in exile bool LookupAccountName ([, MarshalAs (UnmanagedType.LPTStr)] string systemName, [, MarshalAs (UnmanagedType.LPTStr)] string account, IntPtr sid, Referee integer cbSid, stringbinder referenced denman name, referee int cbReferencedDomainName, use out); [DllImport ( "advapi32.dll", charset = CharSet.Auto, SetLastError = true)] internal static exile bool ConvertSidToStringSid (IntPtr sid, [, outside, MarshalAs (UnmanagedType.LPTStr)] ref string pStringSid); /// & lt; Summary & gt; The method changes the object name (user, group) into the SID string. & Lt; / Summary & gt; /// & lt; Ultimate name = "name" & gt; Object name in the form domain \ object_name. & Lt; / Param & gt; /// & lt; Returns & gt; CID string. & Lt; / Returns & gt; Public Static String GetSid (String Name) {IntPtr _sid = IntPtr.Zero; // In the binary form of the indicator SID string Int _sidLength = 0; // Side buffer size int _domainLength = 0; // Domain name buffer size. Int _use; // Object type stringbilder_domain = new stringbilder (); // stringbilder for domain name Int_error = 0; String _sidString = ""; // function first calls only buffers (SDI, domain name) LookupAccountName (zero, name, _sid, referee _sidLength, _domain, referee _domainLength, gives shape out _use); _error = Marshal.GetLastWin32Error (); If (_error! = 122) // Error 122 (sent to the system call data field is too small) - general practice {throw (new Exception (New Win32Exception (_error). Send a)); } Else {_domain = new stringbilder (_domainLength); // domain names _sid = Marshal.AllocHGlobal (_sidLength) allocates memory; // Sid bool _rc = LookupAccountName (zero, name, _sid, referee _sidLength, _domain, the referee does _domainLength, allocated memory out _use); If (_rc == incorrect) {_error = Marshal.GetLastWin32Error (); Marshal.FreeHGlobal (_sid); Throw (New Exception (New Win32Exception (_error). Message)); } Else {// string _rc = convert binary SID into convert endoderm seed (_sid, ref _sidString); If (_rc == incorrect) {_error = Marshal.GetLastWin32Error (); Marshal.FreeHGlobal (_sid); Throw (New Exception (New Win32Exception (_error). Message)); } Other {Marshall. Freib Global (_sid); Return _sidString; }}}}  

Comments