/// <summary> /// Enumerate the specified stored credentials in the Windows Credential store /// </summary> /// <param name="target">Name of the application or URL for which the credential is used</param> /// <returns>Return a <see cref="List{ICredential}"/> if success, null if target not found, throw if failed to read stored credentials</returns> public static List <ICredential> EnumerateICredentials(string target = null) { IntPtr pCredentials = IntPtr.Zero; uint count = 0; var success = NativeCode.CredEnumerate(target, 0, out count, out pCredentials); if (!success) { var lastError = Marshal.GetLastWin32Error(); if (lastError == (int)NativeCode.CredentialUIReturnCodes.NotFound) { return(null); } throw new CredentialAPIException($"Unable to Enumerate Credential store", "CredEnumerate", lastError); } List <NetworkCredential> networkCredentials = new List <NetworkCredential>(); Credential[] credentials; try { using var criticalSection = new CriticalCredentialHandle(pCredentials); credentials = criticalSection.EnumerateCredentials(count); } catch (Exception) { return(null); } return(credentials.Select(c => c as ICredential).ToList()); }
/// <summary> /// Enumerate the specified stored credentials in the Windows Credential store /// </summary> /// <param name="target">Name of the application or URL for which the credential is used</param> /// <returns>Return a <see cref="List{NetworkCredential}"/> if success, null if target not found, throw if failed to read stored credentials</returns> public static List <NetworkCredential> EnumerateCredentials(string target = null) { IntPtr pCredentials = IntPtr.Zero; uint count = 0; var success = NativeCode.CredEnumerate(target, 0, out count, out pCredentials); if (!success) { var lastError = Marshal.GetLastWin32Error(); if (lastError == (int)NativeCode.CredentialUIReturnCodes.NotFound) { return(null); } throw new Win32Exception(lastError, string.Format("'CredEnumerate' call throw an error (Error code: {0})", lastError)); } List <NetworkCredential> networkCredentials = new List <NetworkCredential>(); Credential[] credentials; try { using (var criticalSection = new CriticalCredentialHandle(pCredentials)) { credentials = criticalSection.EnumerateCredentials(count); } } catch (Exception) { return(null); } return(credentials.Select(c => c.ToNetworkCredential()).ToList()); }