2010-09-18 13 views
9

Para un proyecto estoy construyendo un nuevo front-end para un viejo sistema de script por lotes. Tengo que usar Windows XP y C# con .Net. No quiero tocar este viejo sistema Backend ya que está diseñado en la última década. Así que mi idea es iniciar el programa cmd.exe y ejecutar el script Bash allí. Para esto, usaré la función "sistema" en .Net.Lectura del script de shell Resultado en C# .Net Program

Pero también necesito leer la "Salida de línea de comandos de proceso por lotes" en mi programa C#. Podría redirigirlo a un archivo. Pero tiene que haber una forma de obtener la Salida Estándar del CMD.exe en mi Programa C#.

¡Muchas gracias!

+2

por 'Bash', ¿quieres decir' Batch'? –

+0

@W_P: bash es un shell unix. –

+0

@Brian: Creo que W_P lo sabe. –

Respuesta

3

Sus formas son buenas. Pero solo obtienes toda la Salida al final. Quería la salida cuando el script se estaba ejecutando. Así que aquí está, primero más o menos lo mismo, pero de lo que hice la salida. Si tiene problemas miran: http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.aspx

public void execute(string workingDirectory, string command) 
{ 

    // create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters. 
    // Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit. 
    System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo(workingDirectory + "\\" + "my.bat ", command); 

    procStartInfo.WorkingDirectory = workingDirectory; 

    //This means that it will be redirected to the Process.StandardOutput StreamReader. 
    procStartInfo.RedirectStandardOutput = true; 
    //This means that it will be redirected to the Process.StandardError StreamReader. (same as StdOutput) 
    procStartInfo.RedirectStandardError = true; 

    procStartInfo.UseShellExecute = false; 
    // Do not create the black window. 
    procStartInfo.CreateNoWindow = true; 
    // Now we create a process, assign its ProcessStartInfo and start it 
    System.Diagnostics.Process proc = new System.Diagnostics.Process(); 

    //This is importend, else some Events will not fire! 
    proc.EnableRaisingEvents = true; 

    // passing the Startinfo to the process 
    proc.StartInfo = procStartInfo; 

    // The given Funktion will be raised if the Process wants to print an output to consol      
    proc.OutputDataReceived += DoSomething; 
    // Std Error 
    proc.ErrorDataReceived += DoSomethingHorrible; 
    // If Batch File is finished this Event will be raised 
    proc.Exited += Exited; 
} 

Algo está apagado, pero lo que usted consigue la idea ...

El HacerAlgo esta función es:

void DoSomething(object sendingProcess, DataReceivedEventArgs outLine); 
{ 
    string current = outLine.Data; 
} 

espero que esto ayude

+0

'BeginOutputReadLine()' también es necesario. –

8

A la pregunta actualizada. A continuación, le indicamos cómo puede iniciar cmd.exe para ejecutar un archivo por lotes y capturar el resultado del script en una aplicación C#.

var process = new Process(); 
var startinfo = new ProcessStartInfo("cmd.exe", @"/C c:\tools\hello.bat"); 
startinfo.RedirectStandardOutput = true; 
startinfo.UseShellExecute = false; 
process.StartInfo = startinfo; 
process.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data); // do whatever processing you need to do in this handler 
process.Start(); 
process.BeginOutputReadLine(); 
process.WaitForExit(); 
2

No se puede capturar la salida con la función system, usted tiene que ir un poco más en la API de subproceso.

using System; 
using System.Diagnostics; 
Process process = Process.Start(new ProcessStartInfo("bash", path_to_script) { 
            UseShellExecute = false, 
            RedirectStandardOutput = true 
           }); 
string output = process.StandardOutput.ReadToEnd(); 
process.WaitForExit(); 
if (process.ExitCode != 0) { … /*the process exited with an error code*/ } 

usted parece estar confundido en cuanto a si usted está tratando de ejecutar un script bash o un archivo por lotes. Estos no son la misma cosa. Bash es un shell unix, para el que existen varios puertos de Windows. El "archivo por lotes" es el nombre comúnmente dado a los scripts cmd. El código anterior asume que desea ejecutar un script bash. Si desea ejecutar un script cmd, cambie bash al cmd. Si desea ejecutar una secuencia de comandos bash y bash.exe no está en su PATH, cambie bash a la ruta completa a bash.exe.

+0

lo siento, estoy acostumbrado a decir bash pero quiero Windows cmd Lote skript – Thomas

+0

tanque usted, su código está funcionando muy bien. Dos bits: en la línea 7 hay un soporte para mucho. Segundo bit: después de path_to_script, simplemente deja una manta y puede agregar sus argumentos al script. Muchas gracias a todos, mi jefe está muy contento: D – Thomas

Cuestiones relacionadas