Mar 212013

One of my programs needs to access a shared folder on another system.  Unfortunately, the other system may be on another domain and/or workgroup so the access may not be automatic if credentials had not previously been set up.  When this happens using Explorer you will see a dialog pop up that asks for a login and password for the share you’re trying to access.  The dialog allows you to save the credentials so you don’t have to put them in every time.

In my program I am trying to access a file on a shared folder and if the folder is not accessible the file access just fails and the user is left up to their own to figure out how to fix the problem.

I wanted to be able to pop up the same dialog so the user is encouraged to enter the credentials for the share in the same way that they do for Explorer.  It turns out that this is pretty easy, but it took me a while to figure it out so I thought I’d post the code here in case anyone else needs to do this sort of thing.

bool ConnectToShare()
{
    CString csResource = RemoveSlash(m_csMyNetworkSharedFolder);
    NETRESOURCE nr;
    nr.dwType = RESOURCETYPE_DISK;
    nr.lpLocalName = NULL; // explicitly set this to NULL
    nr.lpRemoteName = csResource.GetBuffer();
    nr.lpProvider = NULL;
    return WNetAddConnection2(&nr, NULL, NULL,
                CONNECT_INTERACTIVE) == NO_ERROR;
}

I call this function after trying, and getting a failure, for accessing the file I want to open. Then, if the function returns true I try to open the file again and, finally, fail if it can’t after the connection is made. Fortunately, it seems to work pretty reliably once the connection is established and the users sees something they recognize instead of my dumb “it just didn’t work” message.

Hope this helps!

Leave a Reply

(required)

(required)