Simple.CredentialManager.Credential.Save C# (CSharp) Method

Save() public method

Saves this instance.
password;The password has exceeded 512 bytes.
public Save ( ) : bool
return bool
        public bool Save()
        {
            CheckNotDisposed();
            UnmanagedCodePermission.Demand();

            var passwordBytes = Encoding.Unicode.GetBytes(Password);
            if (Password.Length > (512))
                throw new ArgumentOutOfRangeException("password", "The password has exceeded 512 bytes.");

            var credential = new NativeMethods.CREDENTIAL
            {
                TargetName = Target,
                UserName = Username,
                CredentialBlob = Marshal.StringToCoTaskMemUni(Password),
                CredentialBlobSize = passwordBytes.Length,
                Comment = Description,
                Type = (int) Type,
                Persist = (int) PersistenceType
            };

            var result = NativeMethods.CredWrite(ref credential, 0);
            if (!result)
                return false;

            LastWriteTimeUtc = DateTime.UtcNow;
            return true;
        }

Usage Example

Ejemplo n.º 1
0
        /// <summary>
        /// Saves the given Network Credential into Windows Credential store
        /// </summary>
        /// <param name="Target">Name of the application/Url where the credential is used for</param>
        /// <param name="credential">Credential to store</param>
        /// <param name="type">CredentialType</param>
        /// <param name="persistenceType">PersistenceType</param>
        /// <returns></returns>
        public static bool SaveCredentials(string Target, NetworkCredential credential, CredentialType type, PersistenceType persistenceType)
        {
            // Go ahead with what we have are stuff it into the CredMan structures.
            Credential cred = new Credential(credential);

            cred.Target          = Target;
            cred.PersistenceType = persistenceType;
            cred.Type            = type;
            bool ret       = cred.Save();
            int  lastError = Marshal.GetLastWin32Error();

            if (!ret)
            {
                throw new Win32Exception(lastError, "CredWrite throw an error");
            }
            return(ret);
        }