Search code examples
c++windowswebwinapinetconnection

How do I make the operating system save my credentials when I use WNetAddConnection2 or WNetAddConnection3?


I wrote a window to enter my username and password to login. I can't save the credential when I use the following method, what should I do

NETRESOURCEW net_resource {0};
net_resource.dwType = RESOURCETYPE_DISK | RESOURCETYPE_ANY;
TCHAR szRemotePath[MAX_PATH] {0};
_tcscpy_s(szRemotePath, MAX_PATH, remote_path.toStdWString().c_str());
net_resource.lpRemoteName = szRemotePath;
status_code = ::WNetAddConnection2(&net_resource, password.toStdWString().c_str(), user.toStdWString().c_str(),
CONNECT_UPDATE_PROFILE | CONNECT_INTERACTIVE | CONNECT_COMMANDLINE | CONNECT_CMD_SAVECRED);

Solution

  • You need to write the credentials into the credential vault, e.g. with CredWriteDomainCredentials. See my answer in this question for an example (written in Delphi but should be very straightforward to convert to C/C++)