Как прочитать сообщение из командного файла из приложения С#

У меня есть пакетный файл, который копирует файл из одной папки в другую. Итак, я хотел бы запустить этот файл из служб 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

Код С#:

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

Можем ли мы помочь мне?


person bircastri    schedule 20.11.2014    source источник


Ответы (1)


Вы можете использовать код ниже внутри вашего цикла:

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)
person giacomelli    schedule 20.11.2014
comment
Но что такое p.StartInfo? - person bircastri; 05.12.2014
comment
Извините, но я не решил свою проблему. Я видел еще один пост, который мы связали в этом посте, но не нашел. Я только что изменил свой пост. - person bircastri; 05.12.2014