Access to a protected network share using Win32 C++

WNetAddConnection2 

DWORD WNetAddConnection2A(
  LPNETRESOURCEA lpNetResource,
  LPCSTR         lpPassword,
  LPCSTR         lpUserName,
  DWORD          dwFlags
);

 

The WNetAddConnection2 function makes a connection to a network resource and can redirect a local device to the network resource.

The WNetAddConnection2 function supersedes the WNetAddConnection function. If you can pass a handle to a window that the provider of network resources can use as an owner window for dialog boxes, call the WNetAddConnection3 function instead.

 

Examples

The following code sample illustrates how to use the WNetAddConnection2 function to make connection to a network resource.

#ifndef UNICODE
#define UNICODE
#endif
#pragma comment(lib, "mpr.lib")

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <Winnetwk.h>

// Need to link with Netapi32.lib and Mpr.lib

int wmain(int argc, wchar_t * argv[])
{

    DWORD dwRetVal;

    NETRESOURCE nr;
    DWORD dwFlags;

    if (argc != 5) {
        wprintf(L"Usage: %s <localname> <remotename> <username> <password>\n",
                argv[0]);
        wprintf(L"       %s X: \\\\contoso\\public testuser testpasswd\n",
                argv[0]);
        exit(1);
    }

    wprintf(L"Calling WNetAddConnection2 with\n");
    wprintf(L"  lpLocalName = %s\n", argv[1]);
    wprintf(L"  lpRemoteName = %s\n", argv[2]);
    wprintf(L"  lpUsername = %s\n", argv[3]);
    wprintf(L"  lpPassword = %s\n", argv[4]);

// Zero out the NETRESOURCE struct
    memset(&nr, 0, sizeof (NETRESOURCE));

// Assign our values to the NETRESOURCE structure.

    nr.dwType = RESOURCETYPE_ANY;
    nr.lpLocalName = argv[1];
    nr.lpRemoteName = argv[2];
    nr.lpProvider = NULL;

// Assign a value to the connection options
    dwFlags = CONNECT_UPDATE_PROFILE;
//
// Call the WNetAddConnection2 function to assign
//   a drive letter to the share.
//
    dwRetVal = WNetAddConnection2(&nr, argv[4], argv[3], dwFlags);
//
// If the call succeeds, inform the user; otherwise,
//  print the error.
//
    if (dwRetVal == NO_ERROR)
        wprintf(L"Connection added to %s\n", nr.lpRemoteName);
    else
        wprintf(L"WNetAddConnection2 failed with error: %u\n", dwRetVal);

    exit(1); 
}

To finish using it do:

DWORD retval = WNetCancelConnection2(L"\\\\server\\share", 0, TRUE);

 

posted @ 2018-09-05 16:14  KeepInYourMind  阅读(416)  评论(0编辑  收藏  举报