• 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>
    ",
                    argv[0]);
            wprintf(L"       %s X: \\contoso\public testuser testpasswd
    ",
                    argv[0]);
            exit(1);
        }
    
        wprintf(L"Calling WNetAddConnection2 with
    ");
        wprintf(L"  lpLocalName = %s
    ", argv[1]);
        wprintf(L"  lpRemoteName = %s
    ", argv[2]);
        wprintf(L"  lpUsername = %s
    ", argv[3]);
        wprintf(L"  lpPassword = %s
    ", 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
    ", nr.lpRemoteName);
        else
            wprintf(L"WNetAddConnection2 failed with error: %u
    ", dwRetVal);
    
        exit(1); 
    }

    To finish using it do:

    DWORD retval = WNetCancelConnection2(L"\\server\share", 0, TRUE);
  • 相关阅读:
    源代码的下载和编译
    Git使用入门
    搭建Android开发环境
    安卓系统移植与驱动开发概述
    第十章
    第九章
    第八章
    第七章读书笔记
    第六章读书笔记
    第五章读书笔记
  • 原文地址:https://www.cnblogs.com/zhanghu52030/p/9592762.html
Copyright © 2020-2023  润新知