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);

 

原文链接: https://www.cnblogs.com/zhanghu52030/p/9592762.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    Access to a protected network share using Win32 C++

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/392066

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月1日 下午3:21
下一篇 2023年4月1日 下午3:21

相关推荐