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

Categories

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

c# - Run elevated process

I am trying to run a cmd command with the following code:

ProcessStartInfo cmd = new ProcessStartInfo("cmd.exe");
cmd.RedirectStandardInput = true;
cmd.RedirectStandardOutput = true;
cmd.RedirectStandardError = true;
cmd.UseShellExecute = false;
cmd.CreateNoWindow = true;
cmd.WindowStyle = ProcessWindowStyle.Hidden;
Process exec = Process.Start(cmd);
exec.StandardInput.WriteLine("sc create "BaliService" binPath= "{0}\BaliService.exe"", Directory.GetCurrentDirectory());

This command requires admin privelages, if I run cmd as administrator and type the command it works perfectly but not when I run this app as admin. I have added

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

to a manifest file which prompts uac each time I open the exe.

I have seen multiple questions on this and they all seem to suggest any processes run under an elevated app will have the same rights but this isn't working for me.

I have tried cmd.Verb = "runas"; but no dice.

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

You need to set UseShellExecute to true for the Verb to be respected and it must be set to 'false' to redirect standard output. You can't do both.

I'm pretty sure Windows also won't allow you to redirect standard input/output/error across the admin/non-admin security boundary. You'll have to find a different way to get output from the program running as admin.

I didn't read this article, but this may give you more information: http://www.codeproject.com/KB/vista-security/UAC__The_Definitive_Guide.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...