将Batch shell脚本输出读入C#.Net程序

Tho*_*mas 13 .net c# windows cmd batch-file

对于一个项目,我正在为旧的Batch脚本系统构建一个新的前端.我必须使用Windows XP和C#与.Net.我不想触及这个旧的后端系统,因为它是在过去的十年中制作的.所以我的想法是启动cmd.exe程序并在那里执行Bash脚本.为此,我将使用.Net中的"系统"功能.

但我还需要将"批处理脚本命令行输出"读回我的C#程序.我可以将它重定向到一个文件.但必须有一种方法可以将标准输出输入CMD.exe到我的C#程序中.

非常感谢你!

Bri*_*sen 10

鉴于更新的问题.以下是如何启动cmd.exe以运行批处理文件并在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();
Run Code Online (Sandbox Code Playgroud)


Tho*_*mas 6

你的方法很好。但最后你只能得到整个输出。我想要脚本运行时的输出。所以这就是,首先几乎相同,但我调整了输出。如果您遇到问题,请查看: 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;
}
Run Code Online (Sandbox Code Playgroud)

事情有些不对劲,但无论你有什么想法......

DoSomething 是这个函数:

void DoSomething(object sendingProcess, DataReceivedEventArgs outLine);
{
   string current = outLine.Data;
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助