Mapping network drives through a program becomes a necessity lots of times. The
reasons could be getting authentication at a very preliminary level
or needing to open a file at a remote machine or writing remote computer management applications.
My venture towards this was to do a basic level authentication class, which worked
wonders together with the NT Domain policies. As the requirements of security were very simple and also the application was meant for only intranet users this mechanism was very much sufficient.
Mapping a network drive:
The most important part of mapping a drive is to populate the USE_INFO_2 structure. This prepares the information required for such a job in the necessary format.
One more important point to be noted is that, the values needed to populate the above structure are supported in UNICODE. A special conversion has to happen, if these values are available as normal ASCII values. An example for the usage is illustrated below.
#include <Windows.h>
#include <LM.h>
#include <tchar.h>
#include <stdio.h>
void main()
{
USE_INFO_2 mUseInfo2;
DWORD rc,error_param123;
wchar_t lszDomain[200];
wchar_t lszLocal[200];
wchar_t lszPwd[200];
wchar_t lszRemote[200];
wchar_t lszUser[200];
mbstowcs(lszDomain, "DOMAIN", 200);
mbstowcs(lszLocal, "", 200);
mbstowcs(lszPwd, "PASSWORD", 200);
mbstowcs(lszRemote, "\\\\MACHINENAME\\C$", 200);
mbstowcs(lszUser, "USERNAME", 200);
memset( &mUseInfo2, '\0', sizeof(mUseInfo2) );
mUseInfo2.ui2_asg_type = USE_WILDCARD;
mUseInfo2.ui2_domainname = (char *)lszDomain;
mUseInfo2.ui2_local = (char *)lszLocal;
mUseInfo2.ui2_password =(char *)lszPwd;
mUseInfo2.ui2_remote =(char *)lszRemote;
mUseInfo2.ui2_username =(char *)lszUser;
rc =
NetUseAdd( NULL, 2, (BYTE *)&mUseInfo2, &error_param123);
if(rc == 0)
{
printf("Authenticated \n");
}
else
{
printf("Error during Drive Mapping
Authentication: %d \n");
}
return ;
}
Note: The application needs to link with NetApi32.lib, in addition to the regular libraries. Otherwise, VC++ throws a linker error.
Deleting a Mapped Network Drive:
This is in fact
very very simple, when compared with mapping. The only function you'll need is NetCancelConnection with a parameter of the Drive name you want to delete.
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <Winnetwk.h>
void main()
{
if(WNetCancelConnection2 (_T("Z:"),0,TRUE) ==
NO_ERROR)
printf("Drive Deleted\n");
else
printf("Unable to delete Error:%d\n",GetLastError());
}
Note: The application needs to link with Mpr.lib, in addition to the regular libraries. Otherwise, VC++ throws a linker error.
Sponsors:
Packet Sniffer for Windows