Executing "systeminfo" cmd command WaitForExit doesn't continue - c#

I try execute systeminfo cmd commnand and I have a problem. My problem is that when it comes to method WaitForExit(), the program doesn't continue. I try
using (var cmd = new Process())
{
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("systeminfo");
cmd.StandardInput.Flush();
cmd.WaitForExit();
var result = cmd.StandardOutput.ReadToEnd();
cmd.StandardInput.Close();
cmd.StandardOutput.Close();
return result;
}

Is there a particular reason you go through cmd here? That's so utterly unnecessary here and also explains your problem. You run an interactive instance of cmd, pretending as if you typed systeminfo and then wait for cmd to exit. Just as a normal interactive instance, it won't do that. It will just sit there, waiting for more commands. Instead, why not just call systeminfo directly?
using (var systeminfo= new Process
{
FileName = "systeminfo",
RedirectStandardOutput = true,
CreateNoWindow = false,
UseShellExecute = false,
})
{
systeminfo.Start();
var result = systeminfo.StandardOutput.ReadToEnd();
systeminfo.WaitForExit();
return result;
}

You can try the following options:
Option 1:
Subscribe to Process.Exited event and when the systeminfo process exits, read the stream to get the result of the process.
Option 2:
Redirect the systeminfo process output to a text file. When process exists event occurs, read the result from the text file.
also instead of cmd.StandardInput.WriteLine("systeminfo"); pass the systeminfo process as the argument. It will provide you more control.
ex: cmd.StartInfo.Arguments = "/C systeminfo.exe";

You must add command to cmd, cmd run that and return results and exit.
Use command like "cmd /c ver" works fine and return windows version.

Related

C# execute, wait, read command's output

I'm trying to read all system information on a windows pc, using C#. Here is my code :
public static string GetSystemInfo()
{
String command = "systeminfo";
ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe");
cmdsi.Arguments = command;
Process cmd = Process.Start(cmdsi);
cmd.WaitForExit();
return cmd.StandardOutput.ReadToEnd();
}
But it just opens a console, doesn't execute systeminfo command.
How this can be solved?
The following snippet will work
public static string GetSystemInfo()
{
var command = "/c systeminfo";
var cmdsi = new ProcessStartInfo("cmd.exe");
cmdsi.Arguments = command;
cmdsi.RedirectStandardOutput = true;
cmdsi.UseShellExecute = false;
var cmd = Process.Start(cmdsi);
var output = cmd.StandardOutput.ReadToEnd();
cmd.WaitForExit();
return output;
}
You should set RedirectStandardOutput to true and read output before calling WaitForExit, otherwise you can get a deadlock, per MSDN
The example avoids a deadlock condition by calling
p.StandardOutput.ReadToEnd before p.WaitForExit. A deadlock condition
can result if the parent process calls p.WaitForExit before
p.StandardOutput.ReadToEnd and the child process writes enough text to
fill the redirected stream. The parent process would wait indefinitely
for the child process to exit.
/c means terminating command line after execution
You need to prepend "/c" to the command
String command = "/c systeminfo";
/c indicates that you want to execute a command that follows
Update
ProcessStartInfo.RedirectStandardOutput needs to be set to true as mentioned in Pavel's Answer.

C# starts some cmd commands but other doesn't

My windows forms app triggers an event:
using System.Diagnostics;
string strCmdText = "'/C ping server1.example.com > C:\\Users\\myusername\\Desktop\\1\\a.txt";
Process.Start("cmd.exe", strCmdText);
When executing, cmd.exe is getting spawned, runs for a while, the output is not displayed, but it is present in the redirected 1.txt file.
However, I need to run query command:
using System.Diagnostics;
string strCmdText = "'/C query user /server:server1.example.com > C:\\Users\\myusername\\Desktop\\1\\a.txt";
Process.Start("cmd.exe", strCmdText);
When executing, it spawns a cmd.exe but just for 1 second, then it dissapears, and the output is not present in the 1.txt file.
Is there any way to see what the query command does before it disappears, like keep it open when executing? Maybe is something interesting in there.
Or, am I doing something wrong? Maybe I need to run the command otherwise?
This way:
string outputProcess = "";
string errorProcess = "";
using (Process process = new Process())
{
process.StartInfo.FileName = yourPath;
process.StartInfo.Arguments = yourArguments;
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
outputProcess = process.StandardOutput.ReadToEnd();
errorProcess = process.StandardError.ReadToEnd();
process.WaitForExit();
}
if you really want to run the code as yours. just replace the "CMD" to "CMD /k"

Activating conda environment from c# code (or what is the differences between manually opening cmd and opening it from c#?)

I want to run a gpu accelerated python script on windows using conda environment (dlwin36).
I’m trying to activate dlwin36 and execute a script:
1) activate dlwin36
2) set KERAS_BACKEND=tensorflow
3) python myscript.py
If I manually open cmd on my machine and write:"activate dlwin36"
it works.
But when I try opening a cmd from c# I get:
“activate is not recognized as an internal or external command, operable program or batch file.”
I tried using the following methods:
Command chaining:
var start = new ProcessStartInfo();
start.FileName = "cmd.exe";
start.Arguments = "/c activate dlwin36&&set KERAS_BACKEND=tensorflow&&python myscript.py";
Process.Start(start).WaitForExit();
(I’ve tested several variations of UseShellExecute, LoadUserProfile and WorkingDirectory)
Redirect standard input:
var commandsList = new List<string>();
commandsList.Add("activate dlwin36");
commandsList.Add("set KERAS_BACKEND=tensorflow");
commandsList.Add("python myscript.py");
var start = new ProcessStartInfo();
start.FileName = "cmd.exe";
start.UseShellExecute = false;
start.RedirectStandardInput = true;
var proc = Process.Start(start);
commandsList.ForEach(command => proc.StandardInput.WriteLine(command));
(I’ve tested several variations of LoadUserProfile and WorkingDirectory)
In both cases, I got the same error.
It seems that there is a difference between manually opening cmd and opening it from c#.
The key is to run activate.bat in your cmd.exe before doing anything else.
// Set working directory and create process
var workingDirectory = Path.GetFullPath("Scripts");
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardInput = true,
UseShellExecute = false,
RedirectStandardOutput = true,
WorkingDirectory = workingDirectory
}
};
process.Start();
// Pass multiple commands to cmd.exe
using (var sw = process.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
// Vital to activate Anaconda
sw.WriteLine("C:\\PathToAnaconda\\anaconda3\\Scripts\\activate.bat");
// Activate your environment
sw.WriteLine("activate your-environment");
// Any other commands you want to run
sw.WriteLine("set KERAS_BACKEND=tensorflow");
// run your script. You can also pass in arguments
sw.WriteLine("python YourScript.py");
}
}
// read multiple output lines
while (!process.StandardOutput.EndOfStream)
{
var line = process.StandardOutput.ReadLine();
Console.WriteLine(line);
}
You need to use the python.exe from your environment. For example:
Process proc = new Process();
proc.StartInfo.FileName = #"C:\path-to-Anaconda3\envs\tensorflow-gpu\python.exe";
or in your case:
start.Arguments = "/c activate dlwin36&&set KERAS_BACKEND=tensorflow&&\"path-to-Anaconda3\envs\tensorflow-gpu\python.exe\" myscript.py";
I spent a bit of time working on this and here's the only thing that works for me: run a batch file that will activate the conda environment and then issue the commands in python, like so. Let's call this run_script.bat:
call C:\Path-to-Anaconda\Scripts\activate.bat myenv
set KERAS_BACKEND=tensorflow
python YourScript.py
exit
(Note the use of the call keyword before we invoke the activate batch file.)
After that you can run it from C# more or less as shown above.
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "cmd.exe";
start.Arguments = "/K c:\\path_to_batch\\run_script.bat";
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
start.WorkingDirectory = "c:\\path_to_batch";
string stdout, stderr;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
stdout = reader.ReadToEnd();
}
using (StreamReader reader = process.StandardError)
{
stderr = reader.ReadToEnd();
}
process.WaitForExit();
}
I am generating the batch file on the fly in C# to set the necessary parameters.
If this is gonna help anyone in the future. I found that you must run the activation from C:\ drive.

C# Run command on command prompt and show the command

I am trying to create an app that starts cmd.exe and send command. It is important that the command is visible on cmd. Here is that I got so far but it doesn't seem to be working. Any idea?
Process myProc = new Process();
myProc.StartInfo.FileName = "cmd.exe";
myProc.StartInfo.RedirectStandardInput = true;
myProc.StartInfo.RedirectStandardOutput = true;
myProc.StartInfo.UseShellExecute = false;
myProc.Start();
StreamWriter sendCommand = myProc.StandardInput;
sendCommand.WriteLine("run.exe --forever"); //I want this command to show up in cmd
When the code above is executed, run.exe is ran but the command does not show up in cmd.
What am I doing wrong?
Here's an addendum to my comment to make it clearer:
Process myProc = new Process();
myProc.StartInfo.FileName = "cmd.exe";
myProc.StartInfo.RedirectStandardInput = true;
//myProc.StartInfo.RedirectStandardOutput = true;
myProc.StartInfo.UseShellExecute = false;
myProc.Start();
System.IO.StreamWriter sendCommand = myProc.StandardInput;
sendCommand.WriteLine("run.exe --forever");
This will allow everything outputted by cmd to show in the cmd console.
why you are using the streamwriter ?
you can use the Arguments
myProc.StartInfo.Arguments="run.exe --forever";

How to send commands to cmd in C#

I am coding a program in C# and I need to open cmd.exe, send my commands and get its answers.
I searched around and found some answers to take diagnostics.process in use.
Now, I have two problems:
When I get the output of process, the output is not shown on the cmd consoule itself.
I need to call g95 compiler on the system. When I call it from cmd manually, it is invoked and does well, but when I call it programmatically, I have the this error: "g95 is not recognized as an internal or external ..."
On the other hand, I only found how to send my commands to cmd.exe via arguments and process.standardInput.writeline(). Is there any more convenient method to use. I need to send commands when the cmd.exe is open.
I am sending a part of my code which may help:
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
//myProcess.StartInfo.Arguments = "/c g95";
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardError = true;
myProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(myProcess_OutputDataReceived);
myProcess.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(myProcess_ErrorDataReceived);
myProcess.Start();
myProcess.BeginOutputReadLine();
myProcess.BeginErrorReadLine();
myProcess.StandardInput.WriteLine("g95 c:\\1_2.f -o c:\\1_2.exe");
You can specify the g95 directly and pass the desired command line parameters to it. You don't need to execute cmd first. The command may not be regognized because the settings from the user profile are not loaded. Try setting the property LoadUserProfile in StartInfo to true.
myProcess.StartInfo.LoadUserProfile = true;
This should also set the path variables correctly.
Your code would look something like this:
Process myProcess = new Process();
myProcess.StartInfo = new ProcessStartInfo("g95");
myProcess.StartInfo.Arguments = "c:\\1_2.f -o c:\\1_2.exe"
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.LoadUserProfile = true;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardError = true;
myProcess.OutputDataReceived += myProcess_OutputDataReceived;
myProcess.ErrorDataReceived += myProcess_ErrorDataReceived;
myProcess.Start();
myProcess.BeginOutputReadLine();
myProcess.BeginErrorReadLine();
You are getting the error
"g95 is not recognized as an internal or external ..."
because you haven't added the path to g95.exe in your PATH environment variable. You will get similar result if you open up command prompt and type g95. Here is a link to G95 Windows FAQ page that explains it.

Categories