I am trying to use the NetServerEnum function from the NetApi32 dll, but all I am getting is the error code 5: "Access was denied.". Below is my call to the external dll function.
NetError nEr;
SERVER_TYPE type = SERVER_TYPE.SV_TYPE_WORKSTATION | SERVER_TYPE.SV_TYPE_SERVER; // SV_TYPE_WORKSTATION = 0x00000001 and SV_TYPE_SERVER = 0x00000002
IntPtr bufPtr;
uint entriesread;
uint totalentries;
UInt32 resume_handle_value = 0;
uint MAX_PREFERRED_LENGTH = 0xFFFFFFFF;
nEr = (NetError)NetServerEnum(null, 100, out bufPtr, MAX_PREFERRED_LENGTH, out entriesread, out totalentries, (uint)type, null, ref resume_handle_value);
if (nEr != NetError.NERR_Success)
{
NetApiBufferFree(bufPtr);
throw new InvalidOperationException(nEr);//Throws here with error code 5 -> "Access was denied."
}
The function is declared as so,
[DllImport("Netapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern int NetServerEnum([MarshalAs(UnmanagedType.LPWStr)]string servername, uint level, out IntPtr bufptr, uint prefmaxlen, out uint entriesread, out uint totalentries, uint servertype, [MarshalAs(UnmanagedType.LPWStr)]string domain, ref uint resume_handle);
I tried adding my domain name to the function call, and to call with a different information level but that didn't work either.
Here's a link to the microsoft documentation of the function: https://msdn.microsoft.com/en-us/library/windows/desktop/aa370623%28v=vs.85%29.aspx
Does this function call need a specific set of rights ? I am obviously missing something here but I can't figure out what.
For anyone from the future looking for an answer to any similar kind of issue, I've figured it out.
I was impersonating an Active Directory domain Administrator account that wasn't part of the domain's 'Domain Admins' group. Adding the Administrator account as a member of 'Domain Admins' solved the issue.
So it was a rights issue, I'm guessing it has to do with the local computer's account management system and security settings as I've found out in there that 'MY-PC\Administrators' contains 'MY-DOMAIN\Domain Admins'