我正在根据 this answer 使用 Credential Manager API .引用相关代码片段:
public static Credential ReadCredential(string applicationName)
{
IntPtr nCredPtr;
bool read = CredRead(applicationName, CredentialType.Generic, 0, out nCredPtr);
if (read)
{
using (CriticalCredentialHandle critCred = new CriticalCredentialHandle(nCredPtr))
{
CREDENTIAL cred = critCred.GetCredential();
return ReadCredential(cred);
}
}
return null;
}
它工作得很好,除了当我注销我的 Windows 帐户然后再次登录时,CredRead() 返回 false 并且 Marshal.GetLastWin32Error()
给我 1168
,或 ERROR_NOT_FOUND
。
为什么会有这种行为? Credential Management API 是否仅适用于当前 session ,还是我做错了什么?
编辑:this question下方的评论说:
The documents for the credential management APIs seem to indicate that these credentials are associated with a logon session. Perhaps LogonUser results in a new logon session, so the credentials don't exist there.
但是,我还没有找到任何证据表明凭据管理是特定于 session 的。如果是这样的话,我认为这将毫无用处。
编辑 2:仅作记录,如果您需要获取指示 CredRead() 失败原因的错误编号,请检查 this article 中的 ReadCred() 方法。 .
最佳答案
您可以通过设置 Persist
属性来配置凭据的持久化方式
来自 MSDN ( http://msdn.microsoft.com/en-us/library/windows/desktop/aa374788(v=vs.85).aspx )
CRED_PERSIST_SESSION
CRED_PERSIST_LOCAL_MACHINE
CRED_PERSIST_ENTERPRISE
关于c# - CredRead() 无法跨登录 session 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22528292/