如何从C#应用程序中读取批处理文件中的消息

时间:2014-11-20 12:22:57

标签: c# batch-file robocopy

我有一个批处理文件,可以将文件从一个文件夹复制到另一个文件夹。所以我想从C#windows服务运行这个文件然后我想读取脚本是否生成错误或它是否正常工作。 这是我的午餐代码,但我不知道如何阅读剧本的消息:

脚本代码:

REM
REM This script moves files with results from GOLD server and saves them on MES06 server on .
REM IMPORT folder.
REM
REM Robocopy Options:
REM /R:2     Two retries on failed copies (default is 1 million)
REM /W:5     Wait 5 seconds between retries (default is 30 sec).
REM
REM GOLD QAS Inbound Folder: \\goldqas01.app.pmi\limscihome$\RootDirectory
REM 


for /f "delims=: tokens=2,3" %%j in (F:\MES2GOLD\copy_list_test.txt) do ROBOCOPY.EXE %%j %%j\..\BACKUP *.* /R:2 /W:5 /log+:%%j\..\LOGS\MES2GOLD.log & ROBOCOPY.EXE %%j %%k *.* /R:2 /W:5 /MOV /log+:%%j\..\LOGS\MES2GOLD.log

PAUSE

C#代码:

    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("cmd.exe", @"/c C:\Users\mcastrio\Desktop\GOLD2MES.bat");

        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;
    }

我们可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

您可以在循环中使用以下代码:

var startInfo = p.StartInfo;
startInfo.CreateNoWindow = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UseShellExecute = false;
startInfo.StandardOutputEncoding = Encoding.GetEncoding("ibm850");
startInfo.RedirectStandardOutput = true;
startInfo.FileName = filebatch;
startInfo.Arguments = arguments;

p.Start();
var output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

或者只使用ProcessHelper.Run库中的TestSharp

ProcessHelper.Run(string exePath, string arguments = "", bool waitForExit = true)