Partilhar via


C# sample to open command prompt for other than currently logged user

.Net frameworks 2.0 have some new cool managed APIs. Here is one sample. It is common need to run a process on a user account other than currently logged on user. Following is the simple handy code which I use to open a command prompt with amin previleges, when I am logged on as normal user. There may be many other usage we could find for this Process.Start() API to make our life easier.

using System;
using System.Security;
using System.Diagnostics;

public class RunAs{
public static void Main(string[] args) {
try {
Console.Write(@"User Name [domain\user] : ");
string[] userInfo = (Console.ReadLine()).Split('\\');
SecureString secPass = ReadPassword();
Process.Start("cmd",userInfo[1],secPass,userInfo[0]);

       }
catch(Exception e){
Console.WriteLine("\n"+e.Message);
}
}
public static SecureString ReadPassword()
{
SecureString secPass = new SecureString();
Console.Write("Enter your password : ");
ConsoleKeyInfo key = Console.ReadKey(true);
while(key.KeyChar != '\r')
{
secPass.AppendChar(key.KeyChar);
key = Console.ReadKey(true);
}
return secPass;
}
}

This posting is provided "AS IS" with no warranties, and confers no rights

Comments

  • Anonymous
    October 07, 2004
    C# sample to open command prompt for other than currently logged user
  • Anonymous
    December 12, 2005
    The comment has been removed
  • Anonymous
    September 16, 2008
    You work at Microsoft? This is the dumbest code I've ever seen - has no value, waste of your time man.
  • Anonymous
    December 19, 2009
    this code works if you have a dos-project.sorry you have put up bad code