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

Published 06 October 04 06:02 PM | adarshk 

.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

Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# どっとねっとふぁん blog said on October 7, 2004 10:00 PM:
C# sample to open command prompt for other than currently logged user
# trodriguez said on December 13, 2005 4:53 AM:
this code might be useful for other things but for the purpose you describe it sounds kind of dumb because:

1. It might be easier to right-click the console icon and click "Run as..."; or if you like a command line tool,

2. A better tool ships with Windows (runas.exe)
-try runas /user:<DOMAIN>\<USERNAME> cmd

# Mike said on September 17, 2008 7:27 AM:

You work at Microsoft? This is the dumbest code I've ever seen - has no value, waste of your time man.

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

Search

This Blog

Syndication

Page view tracker