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

前端 未结 3 523
半阙折子戏
半阙折子戏 2020-11-30 21:23

There\'s a question about converting from a SID to an account name; there isn\'t one for the other way around.

How do you convert a username to a SID string, for exa

3条回答
  •  萌比男神i
    2020-11-30 21:53

    using System;
    using System.Management;
    using System.Windows.Forms;
    
    namespace WMISample
    {
    public class MyWMIQuery
    {
        public static void Main()
        {
            try
            {
                ManagementObjectSearcher searcher = 
                    new ManagementObjectSearcher("root\\CIMV2", 
                    "SELECT * FROM Win32_UserAccount where name='Galia'"); 
    
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Win32_UserAccount instance");
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Name: {0}", queryObj["Name"]);
                    Console.WriteLine("SID: {0}", queryObj["SID"]);
                }
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI 
                data: " + e.Message);
            }
          }
        }
    }
    

    /////////Remote:

                ConnectionOptions connection = new ConnectionOptions();
                connection.Username = userNameBox.Text;
                connection.Password = passwordBox.Text;
                connection.Authority = "ntlmdomain:WORKGROUP";
    
                ManagementScope scope = new ManagementScope(
                    "\\\\ASUS\\root\\CIMV2", connection);
                scope.Connect();
    
                ObjectQuery query= new ObjectQuery(
                    "SELECT * FROM Win32_UserAccount"); 
    
                ManagementObjectSearcher searcher = 
                    new ManagementObjectSearcher(scope, query);
    
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Win32_UserAccount instance");
                    Console.WriteLine("-----------------------------------");
                }
    

提交回复
热议问题