Im trying to build a cmd.exe wrapper but i cant figure out how to wait for a process inside the cmd process to finish.
When im run ping.exe in my program, my "inputline" (the path) will output to the console before the ping-command is finished.
I cant use: .WaitForInputIdle(); because I don't have a GUI. "This could be because the process does not have a graphical interface."
Is it even possible to solve or is there any better way to do it?
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ObjectTest
{
class cmd
{
Process cmdProcess;
StreamWriter cmdStreamWriter;
public cmd()
{
//WinAPI.ShowConsoleWindow();
Process();
//WinAPI.HideConsoleWindow();
}
private void Process()
{
StartCmd();
string command = "";
while (command != "exit")
{
Thread.Sleep(100);
cmdProcess.WaitForInputIdle();
Console.Write(Environment.NewLine + Directory.GetCurrentDirectory() + "> ");
command = Console.ReadLine();
SendCommand(command);
}
}
private void StartCmd()
{
cmdProcess = new Process();
cmdProcess.StartInfo.FileName = "cmd.exe";
cmdProcess.StartInfo.UseShellExecute = false;
cmdProcess.StartInfo.CreateNoWindow = true;
cmdProcess.StartInfo.RedirectStandardOutput = true;
cmdProcess.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
cmdProcess.ErrorDataReceived += new DataReceivedEventHandler(SortOutputHandler);
cmdProcess.StartInfo.RedirectStandardInput = true;
cmdProcess.Start();
cmdStreamWriter = cmdProcess.StandardInput;
cmdProcess.BeginOutputReadLine();
}
private void SendCommand(string command)
{
cmdStreamWriter.WriteLine(command);
}
private void btnQuit_Click(object sender, EventArgs e)
{
cmdStreamWriter.Close();
cmdProcess.WaitForExit();
cmdProcess.Close();
}
private static void SortOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!string.IsNullOrEmpty(outLine.Data))
{
Console.WriteLine(outLine.Data);
}
}
}
}