Start Process with administrator right in C#
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 T开发者_如何学Goask every day.
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.
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.
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();
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.
I found it, I need to set the Scheduled Task to run the application with highest privileges in General settings.
精彩评论