Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use c# run batch file as Administrator to install windows services

I have create a batch file which use to install my program as windows services. Content of the batch file:

> C:\Project\Test\InstallUtil.exe
> "C:\Project\Test\ROServerService\Server\bin\Debug\myservices.exe"

Currently it needs the user to right-click the batch file and 'Run as Administrator' in order to success. How do we avoid 'Run as Administrator'? I mean can we use some command in the batch file to tell Windows to run this batch file as administrator?

like image 921
Wilson Avatar asked Jul 12 '16 06:07

Wilson


People also ask

How is C used?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

How do I use C on my computer?

It is a bit more cryptic in its style than some other languages, but you get beyond that fairly quickly. C is what is called a compiled language. This means that once you write your C program, you must run it through a C compiler to turn your program into an executable that the computer can run (execute).


1 Answers

This way worked for me in the past:

string exe = @"C:\Project\Test\InstallUtil.exe";
string args = @"C:\Project\Test\ROServerService\Server\bin\Debug\myservices.exe";
var psi = new ProcessStartInfo();
psi.CreateNoWindow = true; //This hides the dos-style black window that the command prompt usually shows
psi.FileName = @"cmd.exe";
psi.Verb = "runas"; //This is what actually runs the command as administrator
psi.Arguments = "/C " + exe + " " + args;
try {
    var process = new Process();
    process.StartInfo = psi;
    process.Start();
    process.WaitForExit();
}
catch (Exception){
    //If you are here the user clicked decline to grant admin privileges (or he's not administrator)
}

Note that I'm running the commands in your batch file directly here, but of course you can also run the batch file itself:

string bat = @"C:\path\to\your\batch\file.bat";
var psi = new ProcessStartInfo();
psi.CreateNoWindow = true; //This hides the dos-style black window that the command prompt usually shows
psi.FileName = @"cmd.exe";
psi.Verb = "runas"; //This is what actually runs the command as administrator
psi.Arguments = "/C " + bat;
like image 102
Master_T Avatar answered Oct 20 '22 19:10

Master_T