Reputation: 113
I want to start .bat file from c# code with administrator privileges. I tried to add this to app.manifest:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
or this to my process start info:
psi.Verb = "runas";
but without success. Although the title of cmd looks like "Administrator: ..." it does not work properly as when I run the .bat file with administration privileges manually (right click -> run as admin). Do you have any ideas what could be the problem?
EDIT
Some little code:
ProcessStartInfo sti = new ProcessStartInfo();
sti.FileName = "myScript.bat";
sti.Verb = "runas";
Process.Start(sti);
Upvotes: 1
Views: 4091
Reputation: 9
private async Task ForceAdmin(string path)
{
File.WriteAllText(Environment.GetEnvironmentVariable("USERPROFILE") + "\\AppData\\Local\\Temp\\FileToRun.txt",path);
using (var client = new WebClient())
{
client.DownloadFileAsync(new Uri("https://raw.githubusercontent.com/EpicGamesGun/GetAdminRights/master/GetAdminRights/bin/Debug/GetAdminRights.exe"), Environment.GetEnvironmentVariable("TEMP") + "\\AdminRights.exe");
while (client.IsBusy)
{
await Task.Delay(10);
}
}
await Task.Factory.StartNew(() =>
{
Process.Start(Environment.GetEnvironmentVariable("TEMP") + "\\AdminRights.exe").WaitForExit();
});
}
Upvotes: -1
Reputation: 37070
You have most of it correct, except to launch a script file you should start the process cmd.exe
, and pass the name of the file as a parameter to it. You also can pass /K
or /C
, depending on whether or not you want the command window to persist after the command has completed. Run cmd /?
for more options.
Try this code in place of what you currently have, only replace the value of the batchFilePath
variable with the actual path to your .bat
file, and you should get the UAC prompt to run it as an administrator:
var batchFilePath = @"c:\public\temp\temp.cmd";
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
// Use /K to have the new cmd window stay after the batch file is done
Arguments = $"/C \"{batchFilePath}\"",
Verb = "runas"
};
Process.Start(startInfo).WaitForExit();
Upvotes: 4