2

I'm trying to access a network drive (\servername or \ipadress). The idea is that the drive is accessed 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)?

scigor
  • 1,603
  • 5
  • 24
  • 38
  • 1
    `\\myremotenetworkdrive` looks more like a server name; did you mean something like `\\server\share`? – Nate Jan 20 '11 at 15:14
  • yes, there just files on the server, which are accessed in windows usually with entering "\\bla\folders\files" in the explorer. – scigor Jan 20 '11 at 15:20
  • 1
    The `lpRemoteName` parameter to `WNetUseConnection` should be the server name plus the share name (`\\server\share`). It cannot be just the server name, nor can it include the file name. When you access `\\bla\folders\files`, what you are calling the folder name is actually the *share* name. (And yes, you double the backslashes, so it really looks like: `\\\\servername\\sharename`.) – Nate Jan 20 '11 at 15:28

1 Answers1

2

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.

Mark Wilkins
  • 40,729
  • 5
  • 57
  • 110
  • I had the same issue. it was bizarre because it totally worked using a mapped drive (enough to convert 60 directories worth of files) then it stopped working and I had to switch to the UNC sharename. What the? – FlavorScape Mar 22 '13 at 17:34