2010-09-18 5 views
9

Pour un projet, je construis un nouveau frontal pour un ancien système de script Batch. Je dois utiliser Windows XP et C# avec .Net. Je ne veux pas toucher à ce vieux système Backend tel qu'il a été conçu au cours de la dernière décennie. Donc, mon idée est de démarrer le programme cmd.exe et d'exécuter le script Bash là-bas. Pour cela, je vais utiliser la fonction "système" dans .Net.Lecture du script du shell Batch dans le programme C# .Net

Mais j'ai aussi besoin de lire la "Sortie de ligne de commande du script Batch" dans mon programme C#. Je pourrais le rediriger dans un fichier. Mais il doit y avoir un moyen d'obtenir la sortie standard de CMD.exe dans mon programme C#.

Merci beaucoup!

+2

par 'Bash', voulez-vous dire' Batch'? –

+0

@W_P: bash est un shell unix. –

+0

@Brian: Je pense que W_P le sait. –

Répondre

3

Vos chemins sont bons. Mais vous obtenez seulement la sortie entière à la fin. Je voulais la sortie lorsque le script était en cours d'exécution. Alors voilà, tout d'abord à peu près la même chose, mais j'ai twissé la sortie. Si vous avez des problèmes regarder: 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; 
} 

Quelque chose est éteint, mais tout ce que vous avez l'idée ...

Le DoSomething est cette fonction:

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

Hope this helps

+0

'BeginOutputReadLine()' est également nécessaire. –

8

Compte tenu de la question mise à jour. Voici comment vous pouvez lancer cmd.exe pour exécuter un fichier de commandes et capturer la sortie du script dans une application 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

Vous ne pouvez pas capturer la sortie avec la fonction system, vous devez aller un peu plus profondément dans l'API de sous-processus. Vous semblez être confus quant à savoir si vous essayez d'exécuter un script bash ou un fichier séquentiel. Ce ne sont pas les mêmes choses. Bash est un shell Unix, pour lequel plusieurs ports Windows existent. "Batch file" est le nom couramment donné aux scripts cmd. Le code ci-dessus suppose que vous voulez exécuter un script bash. Si vous souhaitez exécuter un script cmd, remplacez bash par cmd. Si vous voulez exécuter un script bash et que bash.exe n'est pas sur votre PATH, remplacez bash par le chemin d'accès complet au bash.exe.

+0

désolé, im utilisé pour dire bash mais je veux Windows cmd Batch skript – Thomas

+0

vous réservoir, votre code fonctionne bien. Deux bits: A la ligne 7 il y a un crochet à beaucoup. Deuxième bit: après path_to_script, vous laissez juste une couverture et vous pouvez ajouter vos arguments au script. Merci beaucoup à tous, mon patron est très content: D – Thomas

Questions connexes