Download source files - 6 Kb
Download demo project - 7 Kb
Introduction
The sample code below shows the API's and code necessary to enumerate the servers
on a domain. The ServerType enum determines the filter for the NetServerEnum call.
The tricky part (I found) was using the unsafe
keyword to actually get the pointer to the array of structures,
and then marshalling the pointers to strings (server names) back into managed code. I spent a couple of hours trying
to get this to work...but the frustration has paid off.
The demo project contains a usercontrol that implements the NetServerEnum API. The user of the control
then only has to set the ServerType property, and the drop-down will be populated.
public enum ServerTypeEnum
{
steNone = 0,
steWorkstation = 0x00000001,
steAll = 0x00000002,
steSQLServer = 0x00000004,
steDomainController = 0x00000008
}
[sysimport(dll="netapi32.dll")]
private static extern void NetApiBufferFree([marshal(UnmanagedType.U4)]uint bufptr);
[sysimport(dll="netapi32.dll")]
unsafe private static extern uint NetServerEnum([marshal(UnmanagedType.LPWStr)] string ServerName,
uint level,
[marshal(UnmanagedType.LPVoid)]uint* bufptr,
uint prefmaxlen,
ref uint entriesread,
ref uint totalentries,
uint servertype,
[marshal(UnmanagedType.LPWStr)] string domain,
uint resume_handle);
[System.Runtime.InteropServices.StructLayoutAttribute (LayoutKind.Sequential, CharSet=CharSet.Auto)]
public struct SERVER_INFO_101
{
public int dwPlatformID;
public int lpszServerName;
public int dwVersionMajor;
public int dwVersionMinor;
public int dwType;
public int lpszComment;
}
protected void GetServers()
{
string servername = null;
string domain = "YourDomainName";
uint level = 101, prefmaxlen = 0xFFFFFFFF, entriesread = 0,
totalentries = 0, resume_handle = 0;
cboServers.Items.Clear();
unsafe
{
SERVER_INFO_101* si = null;
SERVER_INFO_101* pTmp;
uint nRes = NetServerEnum(servername, level,
(uint *) &si, prefmaxlen, ref entriesread, ref totalentries,
(uint)_ServerType, domain, resume_handle);
if (nRes == 0)
{
if ((pTmp = si) != null)
{
for (int i = 0; i < entriesread; i++)
{
try
{
cboServers.Items.Add(Marshal.PtrToStringAuto(pTmp->lpszServerName));
}
catch (Exception e)
{
MessageBox.Show(e.Message) ;
}
pTmp++;
}
}
}
NetApiBufferFree((uint)si);
}
}
History
30 May 2002 - updated source files