programmatically run cmd.exe as administrator in vista, C#
Asked Answered
S

2

6

I have a visual studio setup and deployment project. I've added a .cmd script in it. The script would need administrator privileges to run. When user clicks on the setup.exe, UAC prompts the user for Admin permissions. So I assumed that all processes created and called within setup.exe will run in admin capacity. So I made the setup call my console application which contains the following code.

ProcessStartInfo p1 = new ProcessStartInfo();
p1.UseShellExecute = true;
p1.Verb = "runas";
p1.FileName = "cmd.exe";
Process.Start(p1);

So it should've worked as it's run under administrator space.

I want to run cmd.exe through c# process class as an administrator.I'm running windows vista.

I tried didn't work! What can I do?

Stereoisomerism answered 20/3, 2009 at 18:29 Comment(0)
C
10

Try executing the runas command:

...

using System.Diagnostics;

...

string UserName = "user name goes here";
ProcessStartInfo p1 = new ProcessStartInfo();
  p1.FileName = "runas";
  p1.Arguments = String.Format("/env /u:{0} cmd", UserName);
Process.Start(p1);

...

(And I don't think you need an explicit UseShellExecute)

Caseation answered 20/3, 2009 at 18:32 Comment(5)
i want to impersonate the adminstrator. Like it happens in setup.exe automatically. This one asks for password!Stereoisomerism
Did you expect a different result when you try to impersonate an administrator? Otherwise anyone executing code can be an administrator without knowing the password. Doesn't that strike you as a significant security risk?Spiker
i'l rephrase the question. please have a look and comment on it.Stereoisomerism
You meant the UAC prompt? Oh.. :) I'm not sure about that.Caseation
@lucas, any chance you could provide a link or article that explains this in a bit more detail???Linkoski
R
6

Just Try this, This worked for Me.

...

using System.Diagnostics;

...

ProcessStartInfo startInfo = new ProcessStartInfo();
  startInfo.UseShellExecute = true;            
  startInfo.Verb = "runas";
  startInfo.Arguments = "/env /user:" + "Administrator" + " cmd";
Process.Start(startInfo);

...

Ashutosh

Roger answered 18/5, 2009 at 15:3 Comment(1)
Thanku so much for sharing your knowledge . The above code is working for me , but I want to execute "uwfmgr volume protect C:" this command from the cmd how can i do this using ur codeBireme

© 2022 - 2024 — McMap. All rights reserved.