Start Process with administrator right in C#

醉酒当歌 提交于 2019-11-26 23:16:11

问题


I have to start a command line program with System.Diagnostics.Process.Start() and run it as Administrator.

This action will also be run by a Scheduled Task every day.


回答1:


I've just try to use :

Process p = new Process();
p.StartInfo.Verb = "runas";

this works fine if I'm running my program as Administrator, but when the Scheduled Task runs it, it doesn't take the 'runas' in consideration I think.




回答2:


A better secure option to run a process with login and password is use the SecureString class to encrypt the password. Here a sample of code:

string pass = "yourpass";
string name ="login";
SecureString str;
ProcessStartInfo startInfo = new ProcessStartInfo();
char[] chArray = pass.ToCharArray();
fixed (char* chRef = chArray)
{
    str = new SecureString(chRef, chArray.Length);
}
startInfo.Password = str;
startInfo.UserName = name;
Process.Start(startInfo);

You must allow unsafe code in your project properties.

Hope this help.




回答3:


If you are using scheduled tasks, you can set the user and password for the task to run under.

Use the administrator credentials on the task and you will be fine.

With Process.Start, you need to supply the UserName and Password for the ProcessStartInfo:

Process p = new Process("pathto.exe");
p.StartInfo.UserName = "Administrator";
p.StartInfo.Password = "password";
p.Start();



回答4:


Be aware that storing a password in clear text in a program is never secure as long as someone can peruse the application and see what is in it. Using SecureString to convert a stored password into a SecureString password does not make it more secure, because the clear text password would still be present.

The best way to use SecureString is to pass a single character for conversion at a time in someway that does not require having the complete unencrypted password anywhere in memory or on the hard drive. After that character is converted, the program should forget it, and then go on to the next.

This could be done I think only by passing characters through for translation as they are being typed into the console by the user.




回答5:


I found it, I need to set the Scheduled Task to run the application with highest privileges in General settings.



来源:https://stackoverflow.com/questions/4106628/start-process-with-administrator-right-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!