static bool WriteCredential(string targetName, string userName, string password) { if (targetName == null) { throw new ArgumentNullException("targetName"); } if (userName == null) { throw new ArgumentNullException("userName"); } if (password == null) { throw new ArgumentNullException("password"); } var passwordBytes = Encoding.Unicode.GetBytes(password); if (passwordBytes.Length > 512) { throw new ArgumentException("The secret message has exceeded 512 bytes."); } // Go ahead with what we have are stuff it into the CredMan structures. var cred = new Credential { TargetName = targetName, CredentialBlob = password, CredentialBlobSize = (UInt32)passwordBytes.Length, AttributeCount = 0, Attributes = IntPtr.Zero, Comment = null, TargetAlias = null, Type = NativeCredentialType.Generic, Persist = PersistFlags.LocalMachine, UserName = userName, }; var ncred = NativeCredential.GetNativeCredential(cred); // Write the info into the CredMan storage. var didWrite = NativeMethods.CredWrite(ref ncred, 0); Marshal.FreeCoTaskMem(ncred.TargetName); Marshal.FreeCoTaskMem(ncred.CredentialBlob); Marshal.FreeCoTaskMem(ncred.UserName); return(didWrite); }
internal static extern bool CredWrite([In] ref NativeCredential credential, [In] uint flags);