Home > Enterprise >  Control another pc's windows cmd c# (using tcp)
Control another pc's windows cmd c# (using tcp)

Time:06-04

I have a client / server program which runs os commands from one pc on the other one. This is my client code for running the command :

        Process p = new Process();

        p.StartInfo.UseShellExecute = false;
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = $"/c {command}";
        p.Start();

        string output = p.StandardOutput.ReadToEnd();
        string error = p.StandardError.ReadToEnd();
        p.WaitForExit();
        // sending output and errors back to server...

This code is a method which gets a parameter : command (sent from server) However, this work fine until I'm trying to send two commands that are attached to each other, for example :

cd c://
dir

When I try to send these two commands (separately, the user enters one in a row each time in the server), it runs the cd first then the dir in separate processes.

Is there any way to fix this? (e.g. create one process of cmd and every time enter one line and get the output without closing it)

Thanks in advance.

CodePudding user response:

I will admit that I am doing that on the same computer but I am using the events for new data received. An example will help here...

ProcessStartInfo procStartInfo = new ProcessStartInfo("CMD", "");
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardInput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;

errors = "";
lines = "";
proc = new Process();
proc.StartInfo = procStartInfo;
proc.OutputDataReceived  = new DataReceivedEventHandler(proc_OutputDataReceived);
proc.ErrorDataReceived  = new DataReceivedEventHandler(proc_ErrorDataReceived);
proc.Start();
myStreamWriter = proc.StandardInput;
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();

Then there are the event handlers (I will include the one for stdout here - there is one for the error as well):

void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (e.Data != null)
            {
                // Get the new data, show it on screen and store for retrieval.
                string newLine = e.Data.Trim()   Environment.NewLine;
                lines = lines   newLine;
            }
        }

As usual, don't forget to unsubscribe from the events and close the stream when done.

  • Related