access UNC drive/remote network drive in c++
I'm trying to access a network drive (\servername or \ipadress). The idea is that the drive is acc开发者_Python百科essed only through the application and the login on the network drive is supposed to be used only by the application. So far i have found only the WNetUseConnection Function (http://msdn.microsoft.com/en-us/library/aa385482%28VS.85%29.aspx) which looks like something i want. Unfortuanatly i can't get it working. The code looks like:
NETRESOURCE nr;;
nr.dwType = RESOURCETYPE_DISK;
wchar_t remoteName[] = L"\\\\myremotenetworkdrive";
nr.lpRemoteName = remoteName;
wchar_t pswd[] = L"mypswd";
wchar_t usrnm[] = L"usrname";
int ret = WNetUseConnection(NULL, &nr, pswd, usrnm, 0, NULL, NULL, NULL);
std::cerr << "return code: " << ret << std::endl;
The return code is at first 1200 (ERROR_BAD_DEVICE) and after another function call changes to 487 (ERROR_INVALID_ADDRESS). The address (if iam right to put 4 backslashes there, but also tried it with two or without any at all) username and pswd are correct.
So basicly my question is: How do i get the obove code working? Considering my task ist this the right approach (if not how would you do that)?
I believe that you need to clear the NETRESOURCE
structure (or directly initialize all members). A memset prior to setting the other values may help:
memset( &nr, 0, sizeof( nr ));
In addition, you need to specify the share name as pointed out in the comments:
wchar_t remoteName[] = L"\\\\server\\share";
Also, if you want to associate it with a specific drive letter, you can set this member:
nr.lpLocalName = L"z:";
Without clearing the structure or initializing it somehow, elements such as that lpLocalName would have "random" stack data in it and result in undefined behavior.
精彩评论