如何检查网络驱动器的连接?

我有一个应用程序,使用WNetAddConnection2()在我的网络驱动器上长期创建/写入文件.

    NETRESOURCE nr = {0,};
    nr.dwType = RESOURCETYPE_ANY; 
    nr.lpLocalName = nullptr; 
    nr.lpRemoteName = L"\\\\MyNetworkDrive\\MyFolder\\"; 
    nr.lpProvider = nullptr; 

    DWORD ret = WNetAddConnection2 (&nr, L"MyPW", L"MyID", CONNECT_UPDATE_PROFILE); //add connection

    // A few seconds needed to invoke StartWritingFiles();    

    StartWritingFiles();

但是WNetAddConnection2似乎需要如此繁重的工作才能返回,这使得应用程序看起来很冻结.

所以我想我可以避免在与MyNetworkDrive的连接存在时调用它.

我应该寻找哪种API来解决这个问题?

提前致谢.

最佳答案 以上评论是正确的.网络内容不应该在UI线程上完成.但是,如果你不想线程,我相信你想枚举所有打开的连接,看看你想要的资源是否连接.像这样尝试WNetOpenEnum:

#define _WIN32_WINNT 0x0500

#include <windows.h>
#include <Winnetwk.h>
#include <stdio.h>

#pragma comment(lib,"Mpr.lib")

VOID main(){

    HANDLE hEnum = (HANDLE)0;

    DWORD dwError = WNetOpenEnum(RESOURCE_CONNECTED,RESOURCETYPE_DISK,0,NULL,&hEnum);

    if (dwError == NO_ERROR){

        DWORD dwCount = -1;

        CHAR szBuff[1000];

        ZeroMemory(szBuff,sizeof(szBuff));

        DWORD dwSize = sizeof(szBuff);

        dwError = WNetEnumResource(hEnum,&dwCount,szBuff,&dwSize);

        if (dwError == NO_ERROR){

            NETRESOURCE *pnr = (NETRESOURCE*)szBuff;

            for (DWORD d = 0; d < dwCount; d++){

                if (pnr[d].lpRemoteName){

                    printf("%s\n",pnr[d].lpRemoteName);

                }

            }

        }

        WNetCloseEnum(hEnum);

    }else{

        printf("Failed: %u\n",dwError);

    }

}

这有点hackish因为我假设所有连接都适合1000个字节.你可以在这里阅读WNetOpenEnum函数和相关内容:

http://msdn.microsoft.com/en-us/library/windows/desktop/aa385478%28v=vs.85%29.aspx

点赞