2,640
社区成员
发帖
与我相关
我的任务
分享
VC用代码实现映射网络驱动器
转自:http://hi.baidu.com/luoshengwen/blog/item/61712d129665a250f819b8e2.html
一:打开Project->Add Project->Flie选择C:// Program Files/Microsoft Visual Studio/VC98/Lib/MPR.LIB
二:主要实现代码如下:
NETRESOURCE ns;
memset(&ns, 0, sizeof(ns));
ns.lpLocalName = "H:"; //如果不需要驱动器号,这儿可以是NULL
ns.lpRemoteName = "\\\\IP\\Share";//Ip为服务器IP,Share为共享的文件夹
ns.dwType = RESOURCETYPE_DISK;
if (WNetAddConnection2(&ns,"密码,"用户名",0)!=NO_ERROR)
{
MessageBox("连接成功,可以访问网上邻居机器的共享目录了");
}
三:WnetAddConnection2的用法
The WNetAddConnection2 function makes a connection to a network resource. The function can redirect a local device to the network resource.
The WNetAddConnection2 function supersedes the WNetAddConnection function. If you pass a handle to a window that the provider of network resources can use as an owner window for dialog boxes, use the WnetAddConnection3 function.
DWORD WNetAddConnection2(
LPNETRESOURCE lpNetResource, // points to structure that
// specifies connection details
LPCTSTR lpPassword, // points to password string
LPCTSTR lpUsername, // points to user name string
DWORD dwFlags // set of bit flags that specify
// connection options
);
例:
void CNeighborDlg::Redirect(const char *LocalName,const char *RemoteName,const char * UserName,const char *Password)
{
NETRESOURCE nr;
DWORD res;
char szUserName[32],
szPassword[32],
szLocalName[32],
szRemoteName[MAX_PATH];
strcpy(szUserName,UserName);
strcpy(szPassword,Password);
strcpy(szLocalName,LocalName);
strcpy(szRemoteName,RemoteName);
nr.dwType = RESOURCETYPE_ANY;
nr.lpLocalName = szLocalName;
nr.lpRemoteName = szRemoteName;
nr.lpProvider = NULL;
//
res = WNetAddConnection2(&nr, szPassword, szUserName, FALSE);
//
switch(res)
{
case NO_ERROR:
AfxMessageBox("网络驱动器映射成功");
break;
case ERROR_BAD_PROFILE:
AfxMessageBox("ERROR_BAD_PROFILE");
break;
case ERROR_CANNOT_OPEN_PROFILE:
AfxMessageBox("ERROR_CANNOT_OPEN_PROFILE");
break;
case ERROR_DEVICE_IN_USE:
AfxMessageBox("ERROR_DEVICE_IN_USE");
break;
case ERROR_EXTENDED_ERROR:
AfxMessageBox("ERROR_EXTENDED_ERROR");
break;
case ERROR_NOT_CONNECTED:
AfxMessageBox("ERROR_NOT_CONNECTED");
break;
case ERROR_OPEN_FILES:
AfxMessageBox("ERROR_OPEN_FILES");
break;
default:
AfxMessageBox("未知错误,可能需要帐号和密码认证,或者该主机或文件不存在");
break;
}
return;
}