Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

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:ProjectTestInstallUtil.exe
> "C:ProjectTestROServerServiceServerinDebugmyservices.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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This way worked for me in the past:

string exe = @"C:ProjectTestInstallUtil.exe";
string args = @"C:ProjectTestROServerServiceServerinDebugmyservices.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:pathoyouratchfile.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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...