为什么WNetAddConnection2在成功调用WNetCancelConnection2后仍然返回1219?

时间:2012-07-15 15:54:22

标签: c++ windows winapi active-directory

我写了一些代码来连接远程服务器上的某些共享。如果WNetAddConnection2返回ERROR_SESSION_CREDENTIAL_CONFLICT(1219),我将首先通过WNetCancelConnection2取消连接(返回NO_ERROR)。然后重新连接。但WNetAddConnection2仍会返回1219。 为什么这样以及如何解决它?

这是我的代码

BOOL ADDirectorySearch::IPCConnect(CString strServerName, CString strDomainName, CString strUserName, CString strPassWord)
{
    CString strServerNameWithSlash = _T("\\\\") + strServerName; //actually is \\klbnt
    CString strFullUserName = strDomainName + _T("\\") + strUserName; //is domaintest\administrator
    _bstr_t bstrServerNameWithSlash = strServerNameWithSlash;
    _bstr_t bstrFullUserName = strFullUserName;
    _bstr_t bstrPassWord = strPassWord;
    DWORD dwResult;
    NETRESOURCEW netResource;
    memset(&netResource, 0, sizeof(netResource));
    netResource.dwScope = RESOURCE_GLOBALNET;  
    netResource.dwType = RESOURCETYPE_DISK;
    netResource.dwDisplayType = RESOURCEDISPLAYTYPE_GENERIC;  
    netResource.dwUsage = RESOURCEUSAGE_CONNECTABLE;
    netResource.lpProvider = L"";
    netResource.lpRemoteName = bstrServerNameWithSlash;//Remote IP like:\\192.168.1.11
    dwResult = WNetAddConnection2W(&netResource, bstrPassWord, bstrFullUserName, CONNECT_INTERACTIVE);
    if (dwResult == ERROR_SESSION_CREDENTIAL_CONFLICT)
    {
        dwResult = WNetCancelConnection2W(bstrServerNameWithSlash, CONNECT_UPDATE_PROFILE, TRUE);
        if (dwResult == NO_ERROR)
        {
            dwResult = WNetAddConnection2W(&netResource, bstrPassWord, bstrFullUserName, CONNECT_INTERACTIVE);
        }
        else
        {
            //MyMessageBox_Error(_T("IPCConnect Error."), _T("Error"));
            return FALSE;
        }
    }
    if (dwResult == NO_ERROR)
    {
        return TRUE;
    }
    else
    {
        //MyMessageBox_Error(_T("IPCConnect Error."), _T("Error"));
        return FALSE;
    }
}

仅供参考:在cmd中键入“net use”后,我得到了这个,我觉得有些错误:

Status       Local     Remote                    Network

-------------------------------------------------------------------------------
OK                     \\klbnt\NRDC1001          Microsoft Windows Network
The command completed successfully.

1 个答案:

答案 0 :(得分:3)

我现在只是遇到了这个问题,基本上它似乎是由于另一个进程仍然打开文件,即使我指定"true"作为{{的最后一个参数1}}强制关闭连接。一旦我关闭了其他进程,我就能够在连接和重新连接到同一共享的凭据之间成功切换。这是在Windows 2012(64位)上,共享是本地的(由机器名称引用)。

但是如果你想在同一台机器上连接不同的共享,它仍然是一个问题。如果我尝试将WNetCancelConnection2()作为\\mymachine\share1连接到user1作为\\mymachine\share2,则会收到1219错误(即使它处于完全不同的过程中)。在连接到user2之前,我必须在WNetCancelConnnection上明确调用\\mymachine\share1,这意味着在您连接到特定计算机上的共享时,您可能必须首先枚举现有连接并关闭每一个。

相当令人沮丧,我无法理解这里的设计原则。似乎创建临时连接等的标志也不会对此行为产生影响。我真正希望能够做到的是“对于这个线程,连接到这台机器上的这个共享,并作为这个用户,这样所有访问共享文件的尝试都是用该用户的凭据完成的”。这样,其他进程/线程正在做的事情不会导致当前进程/线程出现问题。