WNetAddConnection2

La función WNetAddConnection2 crea una conexión a un recurso de red y puede redirigir un dispositivo local a un recurso de red.

La función WNetAddConnection2 sustituye a la función WNetAddConnection. Si se puede pasar un manipulador de una ventana que el proveedor de recursos de red pueda usar como una ventana propietaria para cuadros de diálogo, invocar la función WNetAddConnection3 en su lugar.

Sintaxis

DWORD WNetAddConnection2(
  LPNETRESOURCE lpNetResource,
  LPCTSTR lpPassword,
  LPCTSTR lpUsername,
  DWORD dwFlags
);

Parámetros

lpNetResource
Un puntero a una estructura NETRESOURCE que especifica detalles de la conexión propuesta, como información sobre el recurso de red, el dispositivo local y el proveedor de recurso de red. Se deben especificar los siguientes miembros de la estructura NETRESOURCE.
MiembroSignificado
dwTypeEl tipo de recurso de red al que conectarse.
Si el miembro lpLocalName apunta a una cadena no vacía, este miembro puede ser igual a RESOURCETYPE_DISK o RESOURCETYPE_PRINT.
Si lpLocalName es NULL, o si apunta a una cadena vacía, dwType puede ser igual a RESOURCETYPE_DISK, RESOURCETYPE_PRINT o RESOURCETYPE_ANY.
Aunque este miembro sea requerido, su información puede ser ignorada por el proveedor del servicio de red.
lpLocalNameUn puntero a una cadena termianda en cero que especifica el nombre de un dispositivo local a redirigir, como "F:" o "LPT1". La cadena se trata de forma case-insensitive.
Si la cadena está vacía o si lpLocalName es NULL, la función crea una conexión al recurso de red sin redirigirla a un dispositivo local.
lpRemoteNameUn puntero a una cadena terminada en cero que especifica el recurso de red al que conectarse. La cadena puede tener hasta MAX_PATH caracteres de longitud, y debe serguir las convenciones de nombres del proveerdor de red.
lpProviderUn puntero a una cadena terminada en cero que especifica el proveedor de red al que conectarse.
Si lpProvider es NULL, o si apunta a una cadena vacía, el sistema operativo intenta determinar el proveedor correcto pasando la cadena apuntada por el miembro lpRemoteName.
Si este miembro no es NULL, el sistema operativo intenta hacer una conexión sólo con el proveedor de red indicado.
Se debe asignar este miembro sólo si se conoce el proveedor de red que se quiere usar. En caso contrario, dejar al sistema operativo determinar qué nombre de proveedor de red mapear.
lpPassword
Un puntero a una cadena constante termianda en cero que especifica la contraseña a usar en la conexión de red.
Si lpPassword es NULL, la función usa la contraseña por defecto asociada con el usuario especificado por el parámetro lpUserName.
Si lpPassword apunta a una cadena vacía, la función no usa contraseña.
Si la conexión falla debido a una contraseña inválida y el valor CONNECT_INTERACTIVE está asignado en el parámetro dwFlags, la función muestra un cuadro de diálogo para que el usuario introduzca la contraseña.
Windows Me/98/95: Este parámetro debe ser NULL o una cadena vacía.
lpUsername
Un puntero a una cadena constante terminada en nulo que especifica un nombre de usuario para hacer la conexión.
Si lpUserName es NULL, la función usa el nombre de usuario por defecto. (El contexto de usuario para el proceso proporciona el nombre de usuario por defecto.)
El parámetro lpUserName se especifica cuando los usuarios quieren conectarse a un recurso de red para el que se ha asignado un nombre de usuario o cuenta distinto del nombre de usuario o cuenta por defecto.
La cadena de nombre de usuario representa un contexto de seguridad. Debe ser específica para un proveedor de red.
Windows Me/98/95: Este parámetro debe ser NULL o una cadena vacía.
dwFlags
Un conjunto de opciones de conexión. Los posibles valores para las opciones de conexión están definidas en el fichero de cabecera Winnetwk.h. Actualmente se pueden usar los siguientes valores.
CONNECT_TEMPORARY 0x00000004 The network resource connection should not be remembered. If this flag is set, the operating system will not attempt to restore the connection when the user logs on again. CONNECT_INTERACTIVE 0x00000008 If this flag is set, the operating system may interact with the user for authentication purposes. CONNECT_PROMPT 0x00000010 This flag instructs the system not to use any default settings for user names or passwords without offering the user the opportunity to supply an alternative. This flag is ignored unless CONNECT_INTERACTIVE is also set. CONNECT_REDIRECT 0x00000080 This flag forces the redirection of a local device when making the connection. If the lpLocalName member of NETRESOURCE specifies a local device to redirect, this flag has no effect, because the operating system still attempts to redirect the specified device. When the operating system automatically chooses a local device, the dwType member must not be equal to RESOURCETYPE_ANY. If this flag is not set, a local device is automatically chosen for redirection only if the network requires a local device to be redirected. Windows Server 2003 and Windows XP: When the system automatically assigns network drive letters, letters are assigned beginning with Z:, then Y:, and ending with C:. This reduces collision between per-logon drive letters (such as network drive letters) and global drive letters (such as disk drives). Note that earlier versions of Windows assigned drive letters beginning with C: and ending with Z:. CONNECT_CURRENT_MEDIA 0x00000200 If this flag is set, then the operating system does not start to use a new media to try to establish the connection (initiate a new dial up connection, for example). CONNECT_COMMANDLINE 0x00000800 If this flag is set, the operating system prompts the user for authentication using the command line instead of a graphical user interface (GUI). This flag is ignored unless CONNECT_INTERACTIVE is also set. Windows XP: This value is supported on Windows XP and later. CONNECT_CMD_SAVECRED 0x00001000 If this flag is set, and the operating system prompts for a credential, the credential should be saved by the credential manager. If the credential manager is disabled for the caller's logon session, or if the network provider does not support saving credentials, this flag is ignored. This flag is ignored unless CONNECT_INTERACTIVE is also set. This flag is also ignored unless you set the CONNECT_COMMANDLINE flag. Windows XP: This value is supported on Windows XP and later. CONNECT_CRED_RESET 0x00002000 If this flag is set, and the operating system prompts for a credential, the credential is reset by the credential manager. If the credential manager is disabled for the caller's logon session, or if the network provider does not support saving credentials, this flag is ignored. This flag is also ignored unless you set the CONNECT_COMMANDLINE flag. Windows Vista: This value is supported on Windows Vista and later.
ValorSignificado
CONNECT_UPDATE_PROFILE
0x00000001
The network resource connection should be remembered. If this bit flag is set, the operating system automatically attempts to restore the connection when the user logs on. The operating system remembers only successful connections that redirect local devices. It does not remember connections that are unsuccessful or deviceless connections. (A deviceless connection occurs when the lpLocalName member is NULL or points to an empty string.) If this bit flag is clear, the operating system does not try to restore the connection when the user logs on.
CONNECT_UPDATE_RECENT
0x00000002
The network resource connection should not be put in the recent connection list. If this flag is set and the connection is successfully added, the network resource connection will be put in the recent connection list only if it has a redirected local device associated with it.

Valor de retorno

Si la función tiene éxito, the return value is NO_ERROR.

If the function fails, the return value can be one of the following error codes or one of the system error codes.

Return code Description ERROR_ACCESS_DENIED The caller does not have access to the network resource. ERROR_ALREADY_ASSIGNED The local device specified by the lpLocalName member is already connected to a network resource. ERROR_BAD_DEV_TYPE The type of local device and the type of network resource do not match. ERROR_BAD_DEVICE The specified device name is not valid. This error is returned if the lpLocalName member of the NETRESOURCE structure pointed to by the lpNetResource parameter specifies a device that is not redirectable. ERROR_BAD_NET_NAME The network name cannot be found. This value is returned if the lpRemoteName member of the NETRESOURCE structure pointed to by the lpNetResource parameter specifies a resource that is not acceptable to any network resource provider, either because the resource name is empty, not valid, or because the named resource cannot be located. ERROR_BAD_PROFILE The user profile is in an incorrect format. ERROR_BAD_PROVIDER The specified network provider name is not valid. This error is returned if the lpProvider member of the NETRESOURCE structure pointed to by the lpNetResource parameter specifies a value that does not match any network provider. ERROR_BAD_USERNAME The specified user name is not valid. ERROR_BUSY The router or provider is busy, possibly initializing. The caller should retry. ERROR_CANCELLED The attempt to make the connection was canceled by the user through a dialog box from one of the network resource providers, or by a called resource. ERROR_CANNOT_OPEN_PROFILE The system is unable to open the user profile to process persistent connections. ERROR_DEVICE_ALREADY_REMEMBERED The local device name has a remembered connection to another network resource. This error is returned if an entry for the device specified by lpLocalName member of the NETRESOURCE structure pointed to by the lpNetResource parameter specifies a value that is already in the user profile for a different connection than that specified in the lpNetResource parameter. ERROR_EXTENDED_ERROR A network-specific error occurred. Call the WNetGetLastError function to obtain a description of the error. ERROR_INVALID_ADDRESS An attempt was made to access an invalid address. This error is returned if the dwFlags parameter specifies a value of CONNECT_REDIRECT, but the lpLocalName member of the NETRESOURCE structure pointed to by the lpNetResource parameter was unspecified. ERROR_INVALID_PARAMETER A parameter is incorrect. This error is returned if the dwType member of the NETRESOURCE structure pointed to by the lpNetResource parameter specifies a value other than RESOURCETYPE_DISK, RESOURCETYPE_PRINT, or RESOURCETYPE_ANY. This error is also returned if the dwFlags parameter specifies an incorrect or unknown value. ERROR_INVALID_PASSWORD The specified password is invalid and the CONNECT_INTERACTIVE flag is not set. ERROR_LOGON_FAILURE A logon failure because of an unknown user name or a bad password. ERROR_NO_NET_OR_BAD_PATH No network provider accepted the given network path. This error is returned if no network provider recognized the lpRemoteName member of the NETRESOURCE structure pointed to by the lpNetResource parameter. ERROR_NO_NETWORK The network is unavailable. Other Use FormatMessage to obtain the message string for the returned error.

Observaciones

On Windows Server 2003 and Windows XP, the WNet functions create and delete network drive letters in the MS-DOS device namespace associated with a logon session because MS-DOS devices are identified by AuthenticationID (a locally unique identifier, or LUID, associated with a logon session.) This can affect applications that call one of the WNet functions to create a network drive letter under one user logon, but query for existing network drive letters under a different user logon. An example of this situation could be when a user's second logon is created within a logon session, for example, by calling the CreateProcessAsUser function, and the second logon runs an application that calls the GetLogicalDrives function. The call to the GetLogicalDrives function does not return network drive letters created by WNet function calls under the first logon. Note that in the preceding example the first logon session still exists, and the example could apply to any logon session, including a Terminal Services session. For more information, see Defining an MS-DOS Device Name. On Windows Server 2003 and Windows XP, if a service that runs as LocalSystem calls the WNetAddConnection2 function, then the mapped drive is visible to all user logon sessions. For Microsoft network providers, the lpRemoteName member of the NETRESOURCE structure pointed to by the lpNetResource parameter can contain an IPv4 address in dotted-decimal notation. An example for a share might be the following: \\192.168.1.1\share For Microsoft network providers on Windows Vista and later, the lpRemoteName member of the NETRESOURCE structure pointed to by the lpNetResource parameter can contain an IPv6 address. However, the IPv6 literal format must be used so that the IPv6 address is parsed correctly. An IPv6 literal address is of the form: ipv6-address with the ':' characters replaced by '-' characters followed by the ".ipv6-literal.net" string. For example, for the following IPv6 address: 2001:4898:9:3:c069:aa97:fe76:2449 an example for a share might be the following: \\2001-4898-9-3-c069-aa97-fe76-2449.ipv6-literal.net\share Other network providers may support the lpRemoteName member of the NETRESOURCE structure pointed to by the lpNetResource parameter that contains an IPv4 or IPv6 address, but this is up to specific network provider. Windows 7 and Windows Server 2008 R2: If the WNetAddConnection2 function is called with explicit user credentials specified in the pUsername and lpPassword to establish a connection with a network resource on a specific server and then called again with either of these parameters as NULL (to use the default user name or default password) to the same server, the call with fail. The error returned will be ERROR_BAD_USERNAME or ERROR_INVALID_PASSWORD.