Autor Beitrag
Määx
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 123



BeitragVerfasst: Fr 07.03.14 12:30 
Hallo zusammen,

ich würde mir ganz gerne einige Konsolen-Ausgaben in meiner App anzeigen lassen. Dazu wollte ich einffach einen Process starten und wie in einer console Befehle ausführen und mir den Rückgabewert anzeigen lassen. Dabei wrde ich jedoch gerne mehrere Befehle hintereinander ausführen in einem Process.
Als Beispiel könnte man zum Beispiel folgendes machen:
Starte die Konsole mit cmd
Führe dir aus
Führe cd hallo aus
Führe dir aus
Als Basis habe ich meinen Process wie folgt gestartet:
ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
myProcess = new Process();
myProcess.StartInfo = new ProcessStartInfo("cmd");
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.Start();
StreamWriter sw = myProcess.StandardInput;
StreamReader sr = myProcess.StandardOutput;

ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
sw.WriteLine("dir");
string s = myProcess.StandardOutput.ReadLine();
while (s!=null){
    Console.WriteLine(s);
    s = myProcess.StandardOutput.ReadLine();

sw.WriteLine("cd hallo");
s = myProcess.StandardOutput.ReadLine();
while (s!=null){
    Console.WriteLine(s);
    s = myProcess.StandardOutput.ReadLine();
}

sw.WriteLine("dir");
s = myProcess.StandardOutput.ReadLine();
while (s!=null){
    Console.WriteLine(s);
    s = myProcess.StandardOutput.ReadLine();
}

sr.Close();
sw.Close();


Dies führt jedoch dazu, dass nur die erste Schleife durchlaufen wird, weil s niemals null wird. Frage ich ab ob s nullOrEmpty ist, bewirkt dies, dass einige DOS-Befehle nur teilweise zurückgegeben werden da im Rückgabewert leerzeilen vorkommen. Und bei einem ReadToEnd bleibt das Programm ebenfalls in der Schleife hängen.

Daher meine Frage wie kann ich verschiedene Befehle auf einem Prozess ausführen? Oder geht das garnicht? Müsste ich für jeden Befehl einen eigenen Process starten?

Vielen Dank!
Määx
Ralf Jansen
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 4708
Erhaltene Danke: 991


VS2010 Pro, VS2012 Pro, VS2013 Pro, VS2015 Pro, Delphi 7 Pro
BeitragVerfasst: Fr 07.03.14 13:05 
Erstens warum nicht einfach ein Batch?
Zweitens würde ich den Output einfach asynchron lesen.

ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
myProcess.OutputDataReceived += (sender, arg) => { Console.WriteLine(arg.Data); };
myProcess.Start();
myProcess.BeginOutputReadLine();

StreamWriter sw = myProcess.StandardInput;
sw.WriteLine("dir");
sw.WriteLine("cd hallo");
sw.WriteLine("dir");
sw.Close();

myProcess.WaitForExit();