How to get list of user accounts on machine using .Net?

by Naveen 10. June 2010 06:17

Here is a code snippet that demonstrates how to get list of user accounts on your windows machine using .Net. Since there are no native .Net APIs to accomplish this task, you will need to use Interop to use Win32 APIs related to user management.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace UserEnvironment
{
 class Program
 {
  static void Main(string[] args)
  {
   Console.WriteLine(Environment.OSVersion.VersionString);
   Console.WriteLine("OS: {0}.{1}", 
    Environment.OSVersion.Version.Major, 
    Environment.OSVersion.Version.Minor);
   Console.WriteLine("****************************************");
   var accounts = GetListOfAccounts();
   if (accounts.Count != 0)
   {
    Console.WriteLine("User accounts on " + 
     System.Environment.MachineName + System.Environment.NewLine);
    foreach (var account in accounts)
    {
     Console.WriteLine(account);
    }
   }
   else
   {
    Console.WriteLine("No user account found!");
   }
  }

  static System.Collections.Specialized.StringCollection GetListOfAccounts()
  {
   int resumeHandle;
   int entriesRead;
   int totalEntries;
   IntPtr bufPtr;

   var userAccounts = new System.Collections.Specialized.StringCollection();
   NetUserWin32.NetUserEnum(null, 0, 2, out bufPtr, -1, 
    out entriesRead, out totalEntries, out resumeHandle);
   if (entriesRead > 0)
   {
    var users = new NetUserWin32.USER_INFO_0[entriesRead];
    IntPtr iter = bufPtr;
    for (int i = 0; i < entriesRead; i++)
    {
     users[i] = (NetUserWin32.USER_INFO_0)Marshal.PtrToStructure(iter, 
                           typeof(NetUserWin32.USER_INFO_0));
     iter = (IntPtr)((int)iter + Marshal.SizeOf(typeof(NetUserWin32.USER_INFO_0)));
     userAccounts.Add(users[i].Username);
    }
    NetUserWin32.NetApiBufferFree(bufPtr);
   }
   return userAccounts;
  }
 }
}

namespace UserEnvironment
{
 public class NetUserWin32
 {
  [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
  public struct USER_INFO_0
  {
   public String Username;
  }

  [DllImport("Netapi32.dll")]
  public extern static int NetUserEnum([MarshalAs(UnmanagedType.LPWStr)]string servername, 
    int level, int filter, out IntPtr bufptr, 
    int prefmaxlen, out int entriesread, out int totalentries,
    out int resume_handle);

  [DllImport("Netapi32.dll")]
  public extern static int NetApiBufferFree(IntPtr Buffer);
	}
}

Give your advice to big bosses and make money

Views: 351

Tags: ,

.Net | C# | Win32 | Windows

Comments are closed

Powered by BlogEngine.NET 1.5.1.7
Theme by Naveen Kohli

By Categories