Skip to content

Get Resource User Name

A small C program that uses WNetGetUser to retrieve the username associated with a mapped network drive, with full error reporting.

Published Oct 12, 1996

When an application connects to a network resource under one account but you need to know which credentials are actually bound to that connection (for example a mapped drive using stored credentials different from the interactive user), WNetGetUser gives you the answer. This snippet calls it against a drive letter and prints a human-readable explanation for every failure code that can come back - handy as a reference when diagnosing why a network path is or isn't accessible.

#include <Windows.H>
#include <WindowsX.H>
#include <Stdio.H>
#include <Stdlib.H>
#include <string.h>
#include <ShellAPI.H>

//////////////////////////////////////////////////////////////////////

int main()
{
	char RBuffer[1024];
	unsigned long SizeOfRBuffer = sizeof(RBuffer);
	DWORD Result = 0;

	Result = WNetGetUser("S:/",RBuffer,&SizeOfRBuffer);

	if(Result == ERROR_SUCCESS)
		printf("Success Getting UserName.\n");
	if(Result == ERROR_NOT_CONNECTED)
		printf("The device specified by lpName is not a redirected device or a connected network name.\n");
	if(Result == ERROR_MORE_DATA)
		printf("More entries are available with subsequent calls.\n");
	if(Result == ERROR_NO_NETWORK)
		printf("No network is present.\n");
	if(Result == ERROR_EXTENDED_ERROR)
		printf("A network-specific error occurred. To get a description of the error, use the WNetGetLastError function.\n");
	if(Result == ERROR_NO_NET_OR_BAD_PATH)
		printf("None of the providers recognized this local name as having a connection. However, the network is not available for at least one provider to whom the connection may belong.\n");

	if(Result == ERROR_SUCCESS)
		printf("User Name %s\n",RBuffer);

	return 0;

}

Swap "S:/" for whichever drive letter or UNC path you want to inspect; the buffer size is updated in place on success so you can re-call if ERROR_MORE_DATA comes back.

An unhandled error has occurred. Reload 🗙