C# Launch command as administrator - c#

I am trying to launch csript as an administrator (the account logged in has admin rights). setting the startinfo.verb to runas does not work.
ProcessStartInfo p1 = new ProcessStartInfo();
p1.UseShellExecute = true;
p1.Verb = "runas";
p1.FileName = "cscript";
p1.Arguments = "I:\\WPKG\\wpkg.js /synchronize /quiet /nonotify";
Process p = new Process();
p.StartInfo = p1;
p.Start();
The only way I can get it to start with privileges is to manually set the username and password. However I cannot hardcode that information or put it into configurations. Is there any way to have the cmd elevate without the login info?
I have also tried adding using (System.Security.Principal.WindowsIdentity.GetCurrent().Impersonate()) around the above code with no luck either.
Note: If I run the bat file directly, it works, if i run with password hardcoded, it works. It only fails to elevate launching from C# without login information.

This utility:
http://jpassing.com/2007/12/08/launch-elevated-processes-from-the-command-line/
may help. Note too the comments in that post.

You have several choices:
Use the runas utility (not verb), and pass in the username and password to . You may need to do this manually once with saving the credentials (only good till a restart).
Pass in the username and password on the ProcessStartInfo (you will need to convert the password to a SecureString.
Use the runas verb (not utility) to interact with UAC, as described in this question.

Related

How to open an application

I wrote this code to open my application - the name of the executable is C# code analyser.exe. When I start it under Windows 7 (I don't know how this behaves under different versions of Windows), it displays the following message.
Do you want to allow to following program to make changes to this computer?
So I want Windows to not display it to me! What must I do to prevent this message from displaing?
System.Diagnostics.Process Process = new System.Diagnostics.Process();
Process.StartInfo.FileName = (System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "C# code analyser.exe"));
Process.StartInfo.WorkingDirectory = (System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "C# code analyser.exe"));
Process.Start();
Use this instead of your code
System.Diagnostics.Process oProcess = new System.Diagnostics.Process();
oProcess.StartInfo.FileName = "HelloWorld.exe";
oProcess.Start();
or you can pass administrator username & password this way
Process.Start(path + "HelloWorld.exe", uname, password, domain);
This analyzer project, most probably, have a manifest that request administration mode to run. This means that it will keep raising UAC if the starter process(your app) is not elevated.
You can try run you application as an administrator (right click-run as admin) and then the analyzer will inherit the elevation and it will not raise the UAC message.

run shell command (manage-bde) as administrator from C#

I need to run "manage-bde" shell command from C# code.
The main application process is already running as administrator and is Elevated.
I used code from : UAC self-elevation example on MS website for confirming the app process is elevated.
(http://code.msdn.microsoft.com/windowsdesktop/CSUACSelfElevation-644673d3)
However, when I try to run manage-bde from the C# code, I get "System can't find file specified".
Process p = new Process();
p.StartInfo.FileName = "C:\\Windows\\System32\\manage-bde.exe";
p.StartInfo.UseShellExecute = true;
p.Start();
As a workaround, I tried to create a batch file that runs the command.
string batchFileName = DateTime.Now.Ticks + ".bat";
StreamWriter writer = new StreamWriter(batchFileName);
writer.WriteLine("manage-bde");
writer.Flush();
writer.Close();
Process p = new Process();
p.StartInfo.FileName = batchFileName;
p.StartInfo.UseShellExecute = true;
p.Start();
The batch file is written , and executed successfully; However, the command "manage-bde" is not recognized.
I changed the code to use the verb "runas" and use admin password and that works, but I want the batch file to work without the need for providing the admin password. The current logged in user is already administrator on the computer but the batch file is not getting executed with the existing admin privileges . I need the batch file to execute and manage-bde to run successfully.
Your help or advice will be very highly appreciated :)
ps: some commands other than manage-bde work fine without need for admin runas.
The reason of the behavior I encountered was the Windows File System Redirector.
In most cases, whenever a 32-bit application attempts to access %windir%\System32, the access is redirected to %windir%\SysWOW64
https://msdn.microsoft.com/en-us/library/windows/desktop/aa384187%28v=vs.85%29.aspx
My application build was 32 bits. Whenever it tried to access System32 windows automatically redirected it to SysWow64 which does not contain "manage-bde.exe". I changed the build to 64 bits and then the application could access manage-bde.exe from System32
Even if you're running as the Administrator user, you're not fully elevated if UAC is running. Meaning that you'll have either the UAC prompt come up or you'll be prompted for a password.
The only real way you could get around that is to run your application elevated first, or to write a service that runs with elevated permissions to start your new process.
The alternative of course is to disable UAC, but that is undesirable in most situations.

Talking to the exe from the C# code [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Launching a Application (.EXE) from C#?
I am trying to run an exe as a process from my C# code. The exe is a secure one and asks for a password before executing the command. I am unable to pass the password to the exe by any means. When i try to write a standard input it does not take it. Have anyone faced this kind of an issue. If so pls share your work arounds for the scenario. Thanks in advance
I am editing the post to make it a little clear. The exe that i am trying to run is a command line exe. Its a white listing tool provided by mcafee. What i am trying to do is to set the password to the exe so that i can make it secure. the command goes like this
sadmin passwd
once i execute the command it will ask me for the password i want to assign
new password:
once i enter the password it will ask me to re-enter password
re-enter password:
Once the password is set, subsequently when i run other commands on the sadmin, It will prompt me to enter the password
sadmin enable
password:
The password is not an argument to the command. It is passed to the prompt after running the command. So i am unable to achieve this by adding password as an argument to the command.
you can try
Process example= new Process();
example.StartInfo.FileName = "example.exe";
example.StartInfo.Arguments = "arg";
example.Start();
Have you tried using Process.StartInfo.Arguments? Something like this:
Process MyProcess = new Process();
MyProcess.StartInfo.FileName = "PathToExe";
MyProcess.StartInfo.Arguments = "YourArgsHere";
MyProcess.StartInfo.WorkingDirectory = "DesiredWorkingDir(Optional)";
MyProcess.Start();

elevation demand not working for method in winforms app

I have a winforms app that installs other apps in a loop. This works properly on an administrator account in Windows 7, but I have serious issues in a standard account - the app requires elevation in order to write to "Program Files(x86)" folder.
Therefore I am trying to ask for elevation for a specific method (the one that runs the installers) in a winforms c# app, using this code:
[System.Security.Permissions.PrincipalPermission(System.Security.Permissions.SecurityAction.Demand, Role = #"BUILTIN\Administrators")]
After receiving an error, I learned from the web that before calling the method which carries the above attribute, I need to write this:
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
I did this, and the method still throws the following error:
Request for principal permission failed.
Step by step debugging passes the SetPrincipalPolicy line but, when it reaches the method with the Demand atribute, it just throws the same error, as if the SetPrincipalPolicy never existed.
Am I doing something wrong in setting the Demand attribute properly?
Thank you in advance.
LATER EDIT: as requested here is the code that is supposed to trigger the elevation request when installing the app silently (but does not work):
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = principal.IsInRole(WindowsBuiltInRole.Administrator);
if (!hasAdministrativeRight)
{
ProcessStartInfo psi = new ProcessStartInfo(file);
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = true;
psi.Verb = "runas";
//psi.CreateNoWindow = true;
psi.Arguments = modifiers;
try
{
using (Process process = Process.Start(psi))
{
process.WaitForExit();
if (process.HasExited)
return process.ExitCode;
}
}
catch (Win32Exception wex)
{
}
}
What I need, is for that process to pop a dialog asking for username and password for admin, if the app was ran under a Windows Standard User. Only the process started programmatically above should run as admin, the main app itself can remain as a standard user.
This is just not the way UAC works. It is process based, the user only ever gets the "please let me mess with your machine" prompt when you start a new process. With the proper incantation of "I need the user's consent to mess with the machine, please say Yes" signal embedded in the program. Which you do by this answer.
Death to the idea of making it method based. Unreasonable to a programmer, makes sense to a user. User wins.
You can either force your app to always run as an admin. This is how you do that. It is not recommended however for your app to need admin privileges to run.
If you start a Process to run the installer, you can check here how to run the process as an admin.
A third option which Visual Studio uses is that when you do something where you need admin privileges you are prompted to restart the app and it then restarts the app as an admin and you can perform the tasks. Just use the code from the second way to start your app.
The method you've posted to run as admin will check if the user is admin and then start the process as an admin. If the user doesn't have admin rights the app won't even start. A better solution is to always try to run the process as an admin. Then the user will get an UAC prompt with password and username, which an admin can fill in.
public static int RunAsAdmin(string fileName)
{
ProcessStartInfo psi = new ProcessStartInfo(fileName);
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = true;
psi.Verb = "runas";
psi.Arguments = modifiers;
try
{
using (Process process = Process.Start(psi))
{
process.WaitForExit();
if (process.HasExited)
return process.ExitCode;
}
}
catch (Win32Exception wex)
{
}
return 0;
}

How to run a server-side application via ASP.Net(C# or VB)

I wanted to build a front end web page so that I can start and stop various programs on my server remotely. I know that Shell will open something locally, but how can I make an ASP.Net page which activates programs server-side? Googling got me the "Shell" method, but I don't think that works server-side. Any ideas?
Take a look at the System.Diagnostics.Process class. It can allow you to start and stop an executable on the server.
You would have to impersonate an account that has sufficient privileged to run the application, though. You can use the UserName and Password properties of the System.Diagnostics.ProcessStartInfo object that you pass to Process.Start.
Edit
For an example, you could do the following:
var startInfo = new ProcessStartInfo("C:\MyServerApp.exe", "/A /B /C");
startInfo.UserName = "LocalUser";
// It's a bad idea to hard code the password in the app, this is just an example
startInfo.Password = "SomePass";
var process = Process.Start(startInfo);
// Not a good idea to wait in a web app, but you can until the process completes
process.WaitForExit();

Categories