首先在VC项目属性,开发依赖项里添加MPR.lib;然后,配置文件里填入以下信息。
//本地映射盘符
MapDriver=T:
//目标根目录
//MapSharedPath=\\192.168.0.2\D$
MapSharedPath=\\192.168.0.2\QuarkCall
//目标机器用户名
MapUser=administrator
//目标机器密码
MapPassword=administrator
这四个字段信息分别写入全局变量:LocalName,RemoteName,UserName,Password中。
以下是代码:
1 int Redirect(const char *LocalName, const char *RemoteName, const char *UserName, const char *Password) 2 { 3 int nResult = 0; 4 5 NETRESOURCE nr; 6 DWORD res; 7 8 9 char szUserName[32], 10 szPassword[32], 11 szLocalName[32], 12 szRemoteName[MAX_PATH]; 13 14 strcpy(szUserName,UserName); 15 strcpy(szPassword,Password); 16 strcpy(szLocalName,LocalName); 17 strcpy(szRemoteName,RemoteName); 18 19 20 nr.dwType = RESOURCETYPE_ANY; 21 nr.lpLocalName = szLocalName; 22 nr.lpRemoteName = szRemoteName; 23 nr.lpProvider = NULL; 24 25 26 //if(NO_ERROR!=WNetCancelConnection2(szLocalName,0,false)) 27 // printf("断开失败"); 28 29 res = WNetAddConnection2(&nr, szPassword, szUserName, CONNECT_UPDATE_PROFILE); 30 31 switch(res) 32 { 33 case NO_ERROR: 34 g_DebugMsg.Sprintf("网络驱动器映射成功%s\n",RemoteName); 35 nResult = 1; 36 break; 37 case ERROR_BAD_PROFILE: 38 g_DebugMsg.Sprintf("ERROR_BAD_PROFILE\n"); 39 break; 40 case ERROR_CANNOT_OPEN_PROFILE: 41 g_DebugMsg.Sprintf("ERROR_CANNOT_OPEN_PROFILE\n"); 42 break; 43 case ERROR_DEVICE_IN_USE: 44 g_DebugMsg.Sprintf("ERROR_DEVICE_IN_USE\n"); 45 break; 46 case ERROR_EXTENDED_ERROR: 47 g_DebugMsg.Sprintf("ERROR_EXTENDED_ERROR\n"); 48 break; 49 case ERROR_NOT_CONNECTED: 50 g_DebugMsg.Sprintf("ERROR_NOT_CONNECTED\n"); 51 break; 52 case ERROR_OPEN_FILES: 53 g_DebugMsg.Sprintf("ERROR_OPEN_FILES\n"); 54 break; 55 default: 56 g_DebugMsg.Sprintf("未知错误,可能需要帐号和密码认证,或者该主机或文件不存在\n"); 57 break; 58 } 59 return nResult; 60 }