I'm trying to run cmd command as administrator. But the CMD window closes unexpectedly. If CMD window stays I can see the error. I tried to use process.WaitForExit();
I am trying to run the code zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk as administrator.
Here is my code.
//The command that we want to run
string subCommand = zipAlignPath + " -v 4 ";
//The arguments to the command that we want to run
string subCommandArgs = apkPath + " release_aligned.apk";
//I am wrapping everything in a CMD /K command so that I can see the output and so that it stays up after executing
//Note: arguments in the sub command need to have their backslashes escaped which is taken care of below
string subCommandFinal = #"cmd /K \""" + subCommand.Replace(#"\", #"\\") + " " + subCommandArgs.Replace(#"\", #"\\") + #"\""";
//Run the runas command directly
ProcessStartInfo procStartInfo = new ProcessStartInfo("runas.exe");
//Create our arguments
string finalArgs = #"/env /user:Administrator """ + subCommandFinal + #"""";
procStartInfo.Arguments = finalArgs;
//command contains the command to be executed in cmd
using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
proc.StartInfo = procStartInfo;
proc.Start();
}
Is there a way to keep the CMD window running/showing?
You are starting a process from the runas.exe executable file. That's not how to elevate a process.
Instead you need to use shell execute to start your excutable, but use the runas verb. Along these lines:
ProcessStartInfo psi = new ProcessStartInfo(...); // your command here
psi.UseShellExecute = true;
psi.Verb = "runas";
Process.Start(psi);
Capture the output(s) from your process:
proc.StartInfo = procStartInfo;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start()
// string output = proc.StandardOutput.ReadToEnd();
string error = proc.StandardError.ReadToEnd();
proc.WaitForExit();
Then do something with the output.
Note: you shouldn't try to synchronously read both streams at the same time, as there's a deadlock issue. You can either add asyncronous reading for one or both, or just switch back and forth until you're done troubleshooting.
The following method actually works...
private void runCMDFile()
{
string path = #"C:\Users\username\Desktop\yourFile.cmd";
Process proc = new Process();
proc.StartInfo.FileName = path;
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.RedirectStandardOutput = false;
proc.StartInfo.Verb = "runas";
proc.Start();
proc.WaitForExit();
}
Related
I am trying to execute netstat command from my C# code and get "File Not Found" error.
Do I have to specify where "netstat.exe" is?
If so, how would I do it if (hypothetically) netstat and findstr are in two different folders?
Process cmd = new Process();
cmd.StartInfo.FileName = "netstat -a | findstr 5840";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
try
{
cmd.Start();
}
catch (System.ComponentModel.Win32Exception ex)
{
Console.WriteLine(ex.Message);
}
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
StreamReader reader = cmd.StandardOutput;
string output = reader.ReadToEnd();
Console.WriteLine(output);
This is what fixed the problem:
// create the ProcessStartInfo using "cmd" as the program to be run and "/c " as the parameters.
// /c tells cmd that we want it to execute the command that follows and then exit.
string command = "netstat -a | findstr " + sTCPPort;
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
result = proc.StandardOutput.ReadToEnd();
Without seeing the exact it is hard to know the exact issue, but it looks like you may need to cmd.exe and pass your command to it as an argument.
I am trying to run an executable JAR file and it has to run using jre version 1.8.
when I run this command manually from CMD I am getting the jre version as 1.8.
set path=c:\Project Work\jdk1.8.0_66-x64\jre\bin;%PATH%
How can I run this command from C#. I tried the following code but not able to execute the command from c#.
try
{
string command = "set path=c:\\Project Work\\jdk1.8.0_66-x64\\jre\bin;%PATH%";
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
Console.WriteLine(result);
Console.WriteLine(procStartInfo.WorkingDirectory);
Console.ReadLine();
}
catch (Exception objException)
{
// Log the exception
}
Please provide your inputs to execute the command.
I am able to execute the command by following the below steps
1. I have written a batch file with the command
set path=c:\Project Work\jdk1.8.0_66-x64\jre\bin;%PATH%
2. I have named the batch file and executed the batch file from C# program in the following way.
string abc = "abc";
string def = "123";
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "C:\\Users\\90008121\\Desktop\\ClassPathbatch.bat";
proc.StartInfo.Arguments = String.Format("{0} {1}", abc, def);
proc.StartInfo.RedirectStandardError = false;
proc.StartInfo.RedirectStandardOutput = false;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit();
Console.ReadLine();
3. Finally the requirement is met.
Hello I've to Launch the software CFast for a Parametric Analysis. To do this, I want to create a application in C# that runs the core CFast.exe. If I want run the software from cmd.exe and execute it on the file INPUTFILENAME.in I write in prompt:
CFast.exe INPUTFILENAME
In C# I wrote the following code:
Process firstProc = new Process();
firstProc.StartInfo.FileName = #"C:\Users\Alberto\Desktop\Simulazioni Cfast\D\C\N\A3B1\CFAST.exe";
firstProc.StartInfo.Arguments = #"INPUTFILENAME";
firstProc.EnableRaisingEvents = true;
firstProc.Start();
firstProc.WaitForExit();
With this code CFast run but doesn't analyze anything... Seems like don't accept the argument. Hint for this trouble ?
Solved. Mistake in the filename and in the syntax of the command
// setup cmd process
var command = #"CFAST.exe C:\Users\Alberto\Desktop\Simulazioni_Cfast\D\C\N\A3B1\A3B1";
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.RedirectStandardError = true;
procStartInfo.CreateNoWindow = true;
// start process
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
// read process output
string cmdError = proc.StandardError.ReadToEnd();
string cmdOutput = proc.StandardOutput.ReadToEnd();
where A3B1 is the name of the file .IN
Im trying to make C# application that uses hunpos tagger.
Runing hunpos-tag.exe requires three input arguments: model, inputFile, outputFile
In cmd it would look something like this:
hunpos-tag.exe model <inputFile >outputFile
Although, hunpos-tag.exe can be run with just the model, at that point it'll wait for text input (from cmd) which is processed when the tagger receives Ctrl+Enter as input and the results are displayed through standard output. I've been trying to use StandardInput redirection in C# but I don't know how to send the Ctrl+Enter end command (Or if the redirection works at all). The code:
string inputFilePath = path + "\\CopyFolder\\rr";
string pathToExe = path + "\\CopyFolder\\hunpos-tag.exe";
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = pathToExe,
UseShellExecute = false,
RedirectStandardInput = true,
WorkingDirectory = Directory.GetDirectoryRoot(pathToExe),
Arguments = path + "\\CopyFolder\\model.hunpos.mte5.defnpout",
};
try
{
Process _proc = new Process();
_proc.StartInfo.FileName = pathToExe;
_proc.StartInfo.UseShellExecute = false;
_proc.StartInfo.RedirectStandardInput = true;
_proc.StartInfo.Arguments = path + "\\CopyFolder\\model.hunpos.mte5.defnpout";
_proc.Start();
var streamReader = new StreamReader(inputFilePath);
_proc.StandardInput.Write(streamReader.ReadToEnd());
_proc.StandardInput.Flush();
_proc.StandardInput.Close();
_proc.WaitForExit();
}
catch (Exception e)
{
Console.WriteLine(e);
}
When I run the following code the tagger has the following output:
model loaded
tagger compiled
Fatal error: exception Sys_error("Bad file description")
The exception is caused by the .Close() command. The file is valid and works when runned from cmd. Any ideas on how could I send the end command or how to emulate cmd command without using redirection?
It wouldn't work with input redirection so I managed it with running cmd procces and passing it the required command.
using (Process process = new Process())
{
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.WorkingDirectory = #"C:\";
process.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");
// Redirects the standard input so that commands can be sent to the shell.
process.StartInfo.RedirectStandardInput = true;
// Runs the specified command and exits the shell immediately.
//process.StartInfo.Arguments = #"/c ""dir""";
process.OutputDataReceived += ProcessOutputDataHandler;
process.ErrorDataReceived += ProcessErrorDataHandler;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// Send a directory command and an exit command to the shell
process.StandardInput.WriteLine(path + "\\CopyFolder\\hunpos-tag.exe " + path + "\\CopyFolder\\model.hunpos.mte5.defnpout <" + path + "\\CopyFolder\\rr >" + path + "\\CopyFolder\\zz");
process.StandardInput.WriteLine("exit");
process.WaitForExit();
}
When I run he following command from the command line it works fine.
COPY "C:\Windows\System32\winevt\Logs\Application.evtx" "C:\ProgramData\MyCompany\Support\Logs\Application.evtx"
But I want to run it using the following in C#
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + CurrentCommand);
StreamReader.procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
while (!proc.StandardError.EndOfStream)
{
sError = proc.StandardError.ReadLine();
//System.Windows.Forms.MessageBox.Show("ERROR: " + sError);
}
proc.WaitForExit();
// Get the output into a string
sResult = proc.StandardOutput.ReadToEnd();
sResult returns the following error:
The system cannot find the path specified
Why is this?
I guess you need to "escape" the command parameters for the cmd /c argument like
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", string.Format("/c \"{0}\"", CurrentCommand));