Batch process to pass information back to console application window

386 views Asked by At

I have a console application that runs .bat and .vbs files.

The method which starts these processes is as follows:

public void runProcess(string aPath,string aName,string aFiletype)
{
  string stInfoFileName;
  string stInfoArgs;

  if(aFiletype == "bat")
  {
    stInfoFileName = (@aPath + @aName);
    stInfoArgs = string.Empty;
  }
  else
  { //vbs
    stInfoFileName = @"cscript";
    stInfoArgs = "//B //Nologo " + aName;
  }

  this.aProcess.StartInfo.FileName = stInfoFileName;
  this.aProcess.StartInfo.Arguments =  stInfoArgs;
  this.aProcess.StartInfo.WorkingDirectory = @aPath;

  this.aProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
  this.aProcess.Start();

  Console.WriteLine("information passed from batch: ???");

  this.aProcess.WaitForExit(); //<-- Optional if you want program running until your script exit
  this.aProcess.Close();
}

The current .bat files which it is starting are used to send data over ftp (ftp, ftps, or sftp).

When the process is running all information is shown in the process windows e.g. an error might occur, the file is not transferred and a message detailing this is displayed in this "child" process window. Once the process has finished the "child" window disappears along with the messages.

Can I somehow return this useful information to my main console application window?

2

There are 2 answers

4
Martin Prikryl On BEST ANSWER

Check process exit code (Process.ExitCode) and/or capture console output.

See Capturing console output from a .NET application (C#)


Though you should better use some native .NET SFTP/FTP library.

For SFTP, see SFTP Libraries for .NET

For FTP and FTPS, use can use the FtpWebRequest from .NET framework.


If you want all-in-one solution, I can humbly suggest you my WinSCP .NET assembly. With the assembly, you can have the same code for SFTP, FTP and FTPS. Internally, the assembly actually runs WinSCP console application. So it is doing the same thing you are trying to code yourself.

4
Harry Johnston On

If you set this.aProcess.StartInfo.UseShellExecute to false then the child process should use the existing console window.

For batch files, this change also means you'll need to explicitly invoke cmd /c to run them, in exactly the same way you're currently invoking cscript /B to run .vbs scripts.