检索有关网络资源的信息

若要标识拥有资源的网络提供程序,应用程序可以调用 WNetGetResourceInformation 函数,如以下代码示例所示。

以下示例是一个函数 (CheckServer) ,它采用服务器名称作为参数并返回有关该服务器的信息。 首先, 函数调用 ZeroMemory 函数,将内存块的内容初始化为零。 然后,该示例调用 WNetGetResourceInformation 函数,指定一个足够大的缓冲区,以便仅容纳 NETRESOURCE 结构。 例程包括错误处理,以处理此大小的缓冲区不足以容纳 NETRESOURCE 结构成员指向的可变长度字符串的情况。 如果发生此错误,示例将分配足够的内存并再次调用 WNetGetResourceInformation 。 最后,该示例释放分配的内存。

请注意,该示例假定 pszServer 参数指向本地计算机上的某个网络提供程序可识别的服务器名称。

#include <Windows.h>
#include <Winnetwk.h >

// Need to link with Mpr.lib
#pragma comment(lib, "Mpr.lib")
//
// Verify a server on the network. 
//
DWORD
CheckServer( LPTSTR pszServer )
{  
    DWORD dwBufferSize = sizeof(NETRESOURCE);
    LPBYTE lpBuffer;                  // buffer
    NETRESOURCE nr;
    LPTSTR pszSystem = NULL;          // variable-length strings

    //
    // Set the block of memory to zero; then initialize
    // the NETRESOURCE structure. 
    //
    ZeroMemory(&nr, sizeof(nr));

    nr.dwScope       = RESOURCE_GLOBALNET;
    nr.dwType        = RESOURCETYPE_ANY;
    nr.lpRemoteName  = pszServer;

    //
    // First call the WNetGetResourceInformation function with 
    // memory allocated to hold only a NETRESOURCE structure. This 
    // method can succeed if all the NETRESOURCE pointers are NULL.
    // If the call fails because the buffer is too small, allocate
    // a larger buffer.
    //
    lpBuffer = (LPBYTE) malloc( dwBufferSize );
    if (lpBuffer == NULL) 
        return FALSE;

    while ( WNetGetResourceInformation(&nr, lpBuffer, &dwBufferSize, 
                &pszSystem) == ERROR_MORE_DATA)
    {
        lpBuffer = (LPBYTE) realloc(lpBuffer, dwBufferSize);
    }

    // Process the contents of the NETRESOURCE structure and the
    // variable-length strings in lpBuffer and set dwValue. When
    // finished, free the memory.

    free(lpBuffer);

    return TRUE;
}