Running an Application as a Different User in C# and Masking password in Console
Posted on: February 1st, 2009.Category: C#
Today I’ll show you not only one, but two interesting things.
I’ll show you how to run an application from your C# program as a different user (for example Administrator). And I’ll also show you how to mask the password a user enters in your console application.
A more illustrative primer of what I mean you can see on the screen captures below:
![]()
(running a program as Administrator from C#)

(password mask in C# a program)
Source code:
using System; using System.Security; using System.ComponentModel; using System.IO; using System.Collections.Generic; using System.Text; namespace RunAsDifferentUser { class Program { static SecureString getSecureString(String pass) { SecureString password = new SecureString(); foreach (Char c in pass) password.AppendChar(c); return password; } /* This function is to mask our * password input in the console */ public static string ReadPassword() { Stack<string> pass = new Stack<string>(); for (ConsoleKeyInfo consKeyInfo = Console.ReadKey(true); consKeyInfo.Key != ConsoleKey.Enter; consKeyInfo = Console.ReadKey(true)) { if (consKeyInfo.Key == ConsoleKey.Backspace) { try { Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); Console.Write(" "); Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); pass.Pop(); } catch (InvalidOperationException ex) { /* Nothing to delete, go back to previous position */ Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop); } } else { Console.Write("*"); pass.Push(consKeyInfo.KeyChar.ToString()); } } String[] password = pass.ToArray(); Array.Reverse(password); return string.Join(string.Empty, password); } static void Main(String[] args) { String domain = null; String user = "Administrator"; Console.Write("Enter your administrator password: "); SecureString password = getSecureString(ReadPassword()); String filename = "regedit.exe"; try { System.Diagnostics.Process.Start(filename, user, password, domain); Console.WriteLine("\nOur program is being succesfully run! Exiting."); } catch (Win32Exception ex) { Console.Error.WriteLine("\n{0}. Exiting.", ex.Message.ToString()); } } } }
Download this Source Code (MS Visual C# 2005 Express Edition Project)
Please note that if you want to try this example you have to know the Administrator password on your computer. If your administrator account is being renamed you’ll have to change the “user” string to the new name.