CoTaskMemFree() private method

private CoTaskMemFree ( IntPtr pv ) : void
pv System.IntPtr
return void
Example #1
0
        public static void RunProcesssAsUser(String processPath)
        {
            // Setup the flags and variables
            StringBuilder userPassword = new StringBuilder(), userID = new StringBuilder();
            var           credUI = new CREDUI_INFO();

            credUI.pszCaptionText = "Please enter the credentails for " + new ShellItem(processPath).DisplayName;
            credUI.pszMessageText = "DisplayedMessage";
            credUI.cbSize         = Marshal.SizeOf(credUI);
            uint authPackage   = 0;
            var  outCredBuffer = new IntPtr();
            uint outCredSize;
            bool save   = false;
            int  result = CredUIPromptForWindowsCredentials(
                ref credUI,
                0,
                ref authPackage,
                IntPtr.Zero,
                0,
                out outCredBuffer,
                out outCredSize,
                ref save,
                1 /* Generic */);

            var usernameBuf = new StringBuilder(100);
            var passwordBuf = new StringBuilder(100);
            var domainBuf   = new StringBuilder(100);

            int maxUserName = 100;
            int maxDomain   = 100;
            int maxPassword = 100;

            if (result == 0)
            {
                if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName, domainBuf, ref maxDomain, passwordBuf, ref maxPassword))
                {
                    //TO_DO: ms documentation says we should call this but i can't get it to work
                    //SecureZeroMem(outCredBuffer, outCredSize);

                    //clear the memory allocated by CredUIPromptForWindowsCredentials
                    Ole32.CoTaskMemFree(outCredBuffer);

                    var pass = new SecureString();
                    foreach (char _char in passwordBuf.ToString().ToCharArray())
                    {
                        pass.AppendChar(_char);
                    }

                    using (var p = new Process()) {
                        p.StartInfo.UseShellExecute  = true;
                        p.StartInfo.WorkingDirectory = Path.GetDirectoryName(processPath);
                        p.StartInfo.FileName         = processPath;
                        p.StartInfo.UserName         = usernameBuf.ToString();
                        p.StartInfo.Password         = pass;
                        p.StartInfo.Domain           = domainBuf.ToString();
                        p.StartInfo.UseShellExecute  = false;
                        p.Start();
                    }
                }
            }
        }