How to check the connection to a network drive?

I have an application that chronically creates / writes files to my network drive using 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(); 

But WNetAddConnection2 seems to require such hard work to get back, which makes the application look frozen.

So, I suggest that I could avoid the call when the connection to MyNetworkDrive is alive .

What API should I look for to solve this problem?

Thanks in advance.

+4
source share
1 answer

The comments above are correct. Network material should not run in the user interface thread. BUT, if you do not want a thread, I believe that you want to list all open connections in order to find out if your resource is connected. Try WNetOpenEnum, for example:

 #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); } } 

This is a bit hacky, because I assume that all connections fit in 1000 bytes. You can read about the WNetOpenEnum function here too:

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

+2
source

Source: https://habr.com/ru/post/1497726/


All Articles