How can I open a program which requires admin privileges in C#? - c#

I want the C# code to open a program using a shortcut. The program requires admin privileges.
Whilst ensuring Visual Studio is running as administrator,
I have tried:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "FN.lnk";
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.Verb = "runas";
proc.Start();
This fails with the exception: 'The operation was canceled by the user'.
Replacing "FN.lnk" with "cmd.exe" runs a command prompt window with admin privileges...
I have also tried:
System.Diagnostics.Process.Start("CMD.exe", "/K FN.lnk");
which launches an elevated command prompt window, but still says "Access is denied"
If I run cmd as administrator and manually navigate to the folder to run FN.lnk, it works perfectly... which makes this problem even more confusing.

Related

C#: IIS server fails to run a pg_dump Proccess through CMD.exe

I'm trying to create a function that backs up one of my important tables using pg_dump --table. The function runs successfully on my localhost and does the dump. but when it is run by my program through IIS on the server, it doesnt seem to do anything.
my project uses .NET Framework 4.7.2 , Here is my program's code:
try{
var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.WorkingDirectory = "C:\\Website\\Logs\\";
string fileName = startInfo.WorkingDirectory+RandomString();
startInfo.Arguments =
$"/c set PGPASSWORD={userPassword}&pg_dump --file {fileName} --host {Ip} --port 5432 --username {userName} --no-password --verbose --format=d --table public.clients {DB_Name}";
ServerLogs.SaveLog(startInfo.Arguments); //i am saving the logs
startInfo.Verb = "runas"; //run as administrator
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
process.Close();
return "Success";
}catch (Exception x)
{
return x.Message;
}
As u can see, i am logging the arguments field on the server. here is the CMD that was generated and executed :
/c set PGPASSWORD=MyPassword&pg_dump --file C:\Website\Logs\abcd\FileName123123 --host mycluster.eu-north-1.rds.amazonaws.com --port 5432 --username test--no-password --verbose --format=d --table public.clients CRM
this CMD that was created is good, when i copy it to the EC2 server's terminal it runs and dumps the table successfully into my specified path. But when it is run by my program through IIS, it only saves the log, but the proccess itself is not dumping the table. not creating any file. pg_dump is recognized and configured well in my env variables.
1.I was thinking the code is ok because it runs well locally
2.I was thinking the CMD is ok because it runs well on the server's terminal.
3.I tried changing the startInfo.arguments to be "type nul > somefile.txt" to see if IIS has permissions to create files on this folder, and it ran successfully.. so i was thinking this isnt a permission issue.
But I could be wrong. Because it is not working.
I tried several methods and solutions online and I am kinda clueless. I would very much appriciate any help or suggestions. Thank you very much!

Cannot launch .exe with another .exe

I wrote a program to get rid of unexpected errors like NULLs or zeros in .xml file after crash but the "restart" part of code isn't working. It's all good when I run the code in Visual Studio Code but when I use .exe file from dotnet publish function the program just crashes.
I've already tried setting UAC at level 0, UseShellExecute true/false, System.Diagnostics.Process.Start();, running as administrator.
static string exeAdress = #"C:\Program Files (x86)\NaturalPoint\SmartNav\SmartNAV.exe";
// Process.Start(exeAdress); // this isn't working either
Process p = new Process();
p.StartInfo.FileName = exeAdress;
p.StartInfo.UserName = "User";
p.StartInfo.Domain = "Domain";
p.StartInfo.UseShellExecute = true;
p.StartInfo.CreateNoWindow = false;
Actual output is throwing exception but I expect to run the exe without errors:
Unhandled Exception: System.ComponentModel.Win32Exception: The requested operation requires elevation
at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
You need to run your main application as administrator (with elevated permission).
If you can run your application with elevated user then you do not need to supply
p.StartInfo.UserName = "User";
p.StartInfo.Domain = "Domain";
parameters.

Starting a vm "Windows XP Mode" programmatically through a C# program Windows 7

Ok, so I'm having an issue starting the the Windows XP mode VM through a c# program. The command I'm using is vmwindow -file "absolute path to vmcx file" , but the problem is that the command does not work with the cmd prompt that my program kicks off. So, it's very weird. I can go to command prompt on my computer and run this command on my computer and it works, but if i have the same command on my c# program, the command prompt that pops up tells me the "vmwindow" is not a recognized command. I even looked at the paths of each of the command prompts and they're different, but they still both contain "C:\Windows\system32\" which is where vmwindow.exe exists. So, I navigate on the command prompt window that my program populated and the file "vmwindow.exe" is not there, but if I open a command prompt window from my computer and navigate to that folder, it exists there. I can't think of anything else as I already made sure they're both running in administrator mode, and also i tried starting a bat file which contained that command instead of running the command directly. Hope anyone knows anything about this. Here is the code I'm using:
private void button1_Click(object sender, EventArgs e)
{
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.WorkingDirectory = #"<my path>";
startInfo.Arguments = "/k vmwindow.exe -file \"<path to vcmx file>\\Windows XP Mode.vmcx\"";
process.StartInfo = startInfo;
process.Start();
}
What you can do is using Powershell. It has a native integration for Hyper V control and is easy to call from c#
You can see all HV-cmdlets here
a simple command to start your machine would be
Start-VM "Windows 8.1 Pro" -Computername HV-Host1
// etcetc
Stop-VM "Windows 8.1 Pro" -Save
So this should be something like this in C#
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("Start-VM "Windows 8.1 Pro" -Computername HV-Host1");
}
Probably it's because of the bitness setting you compile your program with. ("Platform target" and "Prefer 32-bit" settings under the build tab of the project).
32 and 64 bit processes see different files under System32.
See https://stackoverflow.com/a/950011

CMD prompt opened from Visual Studio won't launch a exe on my computer. Why not?

I have the below code to launch a cmd prompt and from that cmd prompt launch putty.exe with and IP address at the end.
private void btnRouter_Click(Object sender, EventArgs e)
{
MessageBox.Show((string)((Button)sender).Tag);
System.Diagnostics.Process cmd = new System.Diagnostics.Process();
cmd.StartInfo.FileName = #"C:\windows\system32\cmd.exe";
cmd.StartInfo.UseShellExecute = true;
cmd.Start();
cmd.StandardInput.WriteLine("Putty.exe " + ((string)((Button)sender).Tag));
cmd.WaitForExit();
}
Problem is I keep getting an error "StandardIn has not been redirected." from Visual Studio and when I try typing putty.exe in the command window that gets launched I get
"'putty.exe' is not recognized as an internal or external command,
operable program or batch file." which is REALLY weird because if I go to the run line, type cmd and then putty.exe it opens up immediately ever since I added the absolute folder path to the putty application to my system environment path.
Is there a reason the CMD opened from Visual Studio isn't using my Environment Path?
Still don't know why it is happening, however I went back to some previous code and put a copy of putty.exe in my debug folder and it launched successfully this time.
private void btnRouter_Click(Object sender, EventArgs e)
{
MessageBox.Show((string)((Button)sender).Tag);
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "Putty.exe ";
startInfo.Arguments = ((string)((Button)sender).Tag);
myProcess.StartInfo = startInfo;
myProcess.Start();
}
This line will be causing the "StandardIn has not been redirected." error since you are trying to write to stdin and that handle has not be properly setup for input:
cmd.StandardInput.WriteLine("Putty.exe " + ((string)((Button)sender).Tag));
As to this question:
Is there a reason the CMD opened from Visual Studio isn't using my Environment Path?
When a parent process starts a child process that child process will inherit the environment of it's parent.
In other words the new cmd window you're starting will be inheriting the Visual Studio environment, but that does not mean the Visual Studio environment is the same as the environment of the command prompt.
You can test this by starting a command line prompt, running Visual Studio from that command line prompt and then creating your child cmd process.
Now your cmd process should have an environment matching the original command line plus any changes that Visual Studio added to it's copy of the environment.
Use the runas command.
http://technet.microsoft.com/en-us/library/cc771525.aspx
Can you run dir ?

Killing the process running on server

I wrote a program. It kills the process notepad.exe running on computer by and it looks like that:
`
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.WorkingDirectory = #"d:\Windows\System32";
process.StartInfo.Arguments = "/c taskkill /IM notepad.exe";
process.Start();
process.Close();`
I placed this code on my web page. The problem is: when I use the Visual Studio Development server it works. When change to local iis 7.5 it don't. I tried to figure it out, so I even gave the administrator privileges to "DefaultAppPool" or run the whole web page as Administrator (then all the processes as cmd.exe are running as Administrator) but wasn't a solution.

Categories

Resources