internal static void SetLocalAccountPassword()

in LinuxCommunicator/Credentials.cs [358:405]


        internal static void SetLocalAccountPassword(string username, SecureString password)
        {
            CredentialNativeMethods.USER_INFO_1003 info = new CredentialNativeMethods.USER_INFO_1003();
            if (password == null)
            {
                info.sPassword = Marshal.StringToCoTaskMemUni(String.Empty);
            }
            else
            {
                info.sPassword = Marshal.SecureStringToCoTaskMemUnicode(password);
            }

            IntPtr infoPtr = IntPtr.Zero;
            try
            {
                infoPtr = Marshal.AllocHGlobal(Marshal.SizeOf(info));
                Marshal.StructureToPtr(info, infoPtr, false);
                uint errParam;
                int errCode = CredentialNativeMethods.NetUserSetInfo(null, username, /*information level of infoPtr =*/1003, infoPtr, out errParam);

                if (errCode != CredentialNativeMethods.NERR_Success)
                {
                    switch (errCode)
                    {
                        case CredentialNativeMethods.NERR_UserNotFound:
                            throw new ArgumentException("The local user " + username + " is not found.");
                        default:
                            throw new Exception("Error when setting password for local account " + username + ". Error code: " + errCode);
                    }
                }
            }
            finally
            {
                if (info.sPassword != IntPtr.Zero)
                {
                    Marshal.ZeroFreeCoTaskMemUnicode(info.sPassword);
                }

                if (infoPtr != IntPtr.Zero)
                {
                    try
                    {
                        Marshal.FreeHGlobal(infoPtr);
                    }
                    catch { }
                }
            }
        }