Thursday, December 27, 2018

使用 Win32 API 連接網路磁碟 (WNetAddConnection2)



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

#include
#include
#include
#include

#include
#include

// 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 \n",
                argv[0]);
        wprintf(L"       %s X: \\\\contoso\\public testuser testpasswd\n",
                argv[0]);
        exit(1);
    }

_setmode(_fileno(stdout), _O_U16TEXT);
    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);
}
  • Notes 1 : M$ 原廠的 Sample Code 必須加下列 Code 才可在有中文 (Resource) 情況下正常動作 :
_setmode(_fileno(stdout), _O_U16TEXT);

  • Notes 2 : Console Code Page 不是 950 (ex : 現場 PC) 須斟酌加入下列 Code, 並配合 GetConsoleCP()GetConsoleOutputCP() Get / Set 原始設定值 :
SetConsoleCP(950);
SetConsoleOutputCP(950);

No comments:

我負責

 ... + ...........  政策 我負責. 負責推卸責任. (阿不然你以為哩...) 聽說 記錯了 請見諒 深感抱歉.... 抗(國外)疫(苗)中...