ドライブを共有に割り当てる

次の例では、 WNetAddConnection2 関数を呼び出して、ドライブ文字をリモート サーバー共有に接続する方法を示します。 このサンプルでは、呼び出しが成功したかどうかをユーザーに通知します。

次のコード サンプルをテストするには、次の手順を実行します。

  1. 次の行を有効な文字列に変更します。

    szUserName[32] = "myUserName",
    szPassword[32] = "myPassword",
    szLocalName[32] = "Q:",
    szRemoteName[MAX_PATH] = "\\\\products2\\relsys";
    
  2. AddConn2 というコンソール アプリケーションにファイルを追加します。

  3. ライブラリ MPR をリンクします。ライブラリのコンパイラ リストへの LIB。

  4. プログラムAddConn2.EXEをコンパイルして実行します。

#include <windows.h>
#include <stdio.h>
#include <winnetwk.h>
#pragma comment(lib, "mpr.lib")

void main()
{
NETRESOURCE nr;
DWORD res;
TCHAR szUserName[32] = "MyUserName",
    szPassword[32] = "MyPassword",
    szLocalName[32] = "Q:",
    szRemoteName[MAX_PATH] = "\\\\products2\\relsys";
//
// Assign values to the NETRESOURCE structure.
//
nr.dwType = RESOURCETYPE_ANY;
nr.lpLocalName = szLocalName;
nr.lpRemoteName = szRemoteName;
nr.lpProvider = NULL;
//
// Call the WNetAddConnection2 function to assign
//   a drive letter to the share.
//
res = WNetAddConnection2(&nr, szPassword, szUserName, FALSE);
//
// If the call succeeds, inform the user; otherwise,
//  print the error.
//
if(res == NO_ERROR)
  printf("Connection added \n", szRemoteName);
else
  printf("Error: %ld\n", res);
  return;
}