Partager via


Ajout d’une connexion réseau

Pour établir une connexion à une ressource réseau décrite par une structure NETRESOURCE, une application peut appeler laWNetAddConnection2, la WNetAddConnection3ou la fonction WNetUseConnection. L’exemple suivant illustre l’utilisation de la fonction WNetAddConnection2.

L’exemple de code appelle la fonction WNetAddConnection2, en spécifiant que le système doit mettre à jour le profil de l’utilisateur avec les informations, en créant une connexion « mémorisée » ou persistante. L’exemple appelle un gestionnaire d’erreurs défini par l’application pour traiter les erreurs et la fonction TextOut pour l’impression.

DWORD dwResult; 
NETRESOURCE nr; 
//
// Call the WNetAddConnection2 function to make the connection,
//   specifying a persistent connection.
//
dwResult = WNetAddConnection2(&nr, // NETRESOURCE from enumeration 
    (LPSTR) NULL,                  // no password 
    (LPSTR) NULL,                  // logged-in user 
    CONNECT_UPDATE_PROFILE);       // update profile with connect information 
 
// Process errors.
//  The local device is already connected to a network resource.
//
if (dwResult == ERROR_ALREADY_ASSIGNED) 
{ 
    printf("Already connected to specified resource.\n"); 
    return dwResult; 
} 
 
//  An entry for the local device already exists in the user profile.
//
else if (dwResult == ERROR_DEVICE_ALREADY_REMEMBERED) 
{ 
    printf("Attempted reassignment of remembered device.\n"); 
    return dwResult; 
} 
else if(dwResult != NO_ERROR) 
{ 
    //
    // Call an application-defined error handler.
    //
    printf("WNetAddConnection2 failed.\n"); 
    return dwResult; 
} 
 
//
// Otherwise, report a successful connection.
//
printf("Connected to the specified resource.\n"); 

La fonction WNetAddConnection est prise en charge pour la compatibilité avec les versions antérieures de Windows for Workgroups. Les nouvelles applications doivent appeler la fonction WNetAddConnection2 ou la fonction WNetAddConnection3.

Pour plus d’informations sur l’utilisation d’un gestionnaire d’erreurs défini par l’application, consultez Récupération des erreurs réseau.