Please don’t mark as duplicate before read.
After looking a lot of google search I found a lot of code. All the codes are okay but my problem is little bit more.
Suppose, I can execute ‘dir’ command using this below code which gives me perfect output:
static void Main(string[] args)
{
var str=ExecuteCommand("/c dir");
//var str=ExecuteCommand("/c chkdsk C: /f/r/x");
MessageBox.Show(str);
}
static string ExecuteCommand(string cmd)
{
Process proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = cmd;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
return output;
}
But, when I run this command “/c chkdsk C: /f/r/x” then no output comes because it waits for user input(y/n). I want to view output and send y or n from my C# code not by cmd console window.
Related
I'm using C# and I need to execute command in cmd without displaying shell window and retrieve the result, so I did some work like the following:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = command;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
string output = string.Empty;
while (!proc.StandardOutput.EndOfStream) {
output = proc.StandardOutput.ReadLine();
}
But when I executed this code, console returned me this error: 'System.InvalidOperationException'(System.dll).
Why is this problem happening and how can I solve this problem?
I am trying to start a process on Mac and Windows (using Unity) to run FFMPEG to convert a video to a .ogv video. My code is as follows:
string command = "ffmpeg -i '" + filepath + "' -codec:v libtheora -qscale:v 10 -codec:a libvorbis -qscale:a 10 -y '"+workingDir+"/ogv_Video/"+System.IO.Path.GetFileNameWithoutExtension(filepath)+".ogv'";
UnityEngine.Debug.Log("Command: "+command);
try{
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo (workingDir+"/..", command);
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName =workingDir+"/ffmpeg";
//Process.Start (startInfo);
Process p = Process.Start(startInfo);
p.EnableRaisingEvents = true;
string strOutput = p.StandardOutput.ReadToEnd();
UnityEngine.Debug.Log ("Running..."+strOutput);
p.WaitForExit();
UnityEngine.Debug.Log ("Got here. "+strOutput);
int exitCode = p.ExitCode;
UnityEngine.Debug.Log ("Process exit code = "+exitCode);
}
catch(Exception e) {
UnityEngine.Debug.Log ("An error occurred");
UnityEngine.Debug.Log ("Error: "+e);
}
The command executes and does not through any exception. However, it terminates instantly and prints Exit Code 1 which is "Catchall for general errors" -this seems not too helpful!
What am I doing wrong with my code, please?
You'll notice that my code prints out the command in full. If I copy that command and paste it into the terminal, it runs absolutely fine.
It turns out I was setting up the arguments wrongly. Referring to this Stack Overflow question, I was able to produce the expected result with the following code:
try{
Process process = new Process();
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.FileName = Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) +#"ffmpeg";
process.StartInfo.Arguments = command;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
JSONDataObject rtnMsg = new JSONDataObject("StartConvertOK", "-1", new List<string>());
return JsonUtility.ToJson(rtnMsg);
}
It does seem as though the answer was not that different from what I was doing, but it does work!
I want to send commands with arguments and read their answers from cmd. So, I wrote the code below, but it is not working and locks on screen (myString is usually null - ""). I only want to send commands to an opened command prompt. Where is the problem? Thanks in advance. (for example: How can I fetch the result of a ping request?)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace CallBatchFile
{
class Program
{
[STAThread]
static void Main()
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c date";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string myString = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
}
}
cmd /c date is blocking. you can either use
p.StartInfo.Arguments = "/c date /T";
To stop date waiting for input, or give input to cmd
p.StartInfo.RedirectStandardInput = true;
...
p.StandardInput.Write("\n");
..or read async so you can get the output while cmd is waiting for your input:
p.BeginOutputReadLine();
p.OutputDataReceived += (_, e) => Console.WriteLine(e.Data);
This code might help you
string strOutput;
//Starting Information for process like its path, use system shell i.e. control process by system etc.
ProcessStartInfo psi = new ProcessStartInfo(#"C:\WINDOWS\system32\cmd.exe");
// its states that system shell will not be used to control the process instead program will handle the process
psi.UseShellExecute = false;
psi.ErrorDialog = false;
// Do not show command prompt window separately
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
//redirect all standard inout to program
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
//create the process with above infor and start it
Process plinkProcess = new Process();
plinkProcess.StartInfo = psi;
plinkProcess.Start();
//link the streams to standard inout of process
StreamWriter inputWriter = plinkProcess.StandardInput;
StreamReader outputReader = plinkProcess.StandardOutput;
StreamReader errorReader = plinkProcess.StandardError;
//send command to cmd prompt and wait for command to execute with thread sleep
inputWriter.WriteLine("C:\\PLINK -ssh root#susehost -pw opensuselinux echo $SHELL\r\n");
Thread.Sleep(2000);
// flush the input stream before sending exit command to end process for any unwanted characters
inputWriter.Flush();
inputWriter.WriteLine("exit\r\n");
// read till end the stream into string
strOutput = outputReader.ReadToEnd();
//remove the part of string which is not needed
int val = strOutput.IndexOf("-type\r\n");
strOutput = strOutput.Substring(val + 7);
val = strOutput.IndexOf("\r\n");
strOutput = strOutput.Substring(0, val);
MessageBox.Show(strOutput);
I have the following code in my C# application which loaded a batch file silently using command prompt and executed and returned the result to a string:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = #"C:\files\send.bat";
proc.StartInfo.RedirectStandardError = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
string strGetInfo = proc.StandardOutput.ReadToEnd();
strCMDOut = strGetInfo.Substring(strGetInfo.Length - 5, 3);
proc.WaitForExit();
I am trying to avoid my application going out to a different file to execute the batch file, rather I wanted to embed it inside my application. So I changed the above code to this:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "#ECHO ON java com.this.test567 send";
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
proc.StartInfo = startInfo;
proc.Start();
string strGetInfo = proc.StandardOutput.ReadToEnd();
strCMDOut = strGetInfo.Substring(strGetInfo.Length - 5, 3);
When the code executes, I can see the command prompt window for a brief moment before it closes and the execution is not working correctly. How can I fix the issue?
Instead of using cmd.exe just use java directly, you should also redirect standard error and check that after the process ends.
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = #"java.exe";
proc.StartInfo.Arguments = "com.this.test567";
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
string strGetInfo = proc.StandardOutput.ReadToEnd();
if(string.IsNullOrEmpty(strGetInfo))
strGetInfo = proc.StandardError.ReadToEnd();
proc.WaitForExit();
Note that by calling cmd directly, you're effectively making a batch script with whatever you use for in the Arguments Property. Like a .bat file, the command window closes as soon as it's done. To fix this, add a pause command to the end.
startInfo.Arguments = "#ECHO ON java com.this.test567 send\npause";
& seperates commands on a line.
&& executes this command only if previous command's errorlevel is 0.
|| (not used above) executes this command only if previous command's errorlevel is NOT 0
> output to a file
>> append output to a file
< input from a file
| output of one command into the input of another command
^ escapes any of the above, including itself, if needed to be passed to a program
so seperate commands with &
"/k #ECHO ON&java com.this.test567&send"
/k keeps a window open.
so you'll get in cmd
cmd /k #ECHO ON&java com.this.test567&send
I want to delete multiple string lines of files output.which file is redirected.
My code is as follows.
static void Main(string[] args)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd ";
p.StartInfo.UseShellExecute = false;
p.StartInfo.Arguments = "/C ipconfig";
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);
Console.ReadLine();
}
OUTPUT : I give correct answer.but i want only ip address of m/c. Other lines are deleted.
please give the answer of question with changes of code.
Do you really need to run ipconfig? The NetworkInterface class should be able to provide you the information you are looking for without requiring you to run an external process and parse text.
static void Main(string[] args)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd ";
p.StartInfo.UseShellExecute = false;
p.StartInfo.Arguments = "/C net view";
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);
Console.ReadLine();
}
OUTPUT :
server name remark
//st1
//st2
//satishlap
//st6
//st10
command is completed successfully.
I give correct output.I want to only server name(//st1,//st2,//satishlap,//st6,//st10).
other infoemation is deleted. please the answer of my question with the changes of code.