Get Exitcode from CMD using C #

I use the following code to write PATH, EXECUTABLE NAME and ARGUMENTS to a batch file and execute it via CMD using C #. Sometimes the problem is that the application dispenser starts after the batch file is executed. And adding the C # code gives me an exception or any notification.

Why do I want to get Exitcode from CMD to determine if the commands are executed correctly. How to determine the exit code?

  public void Execute()
{
    try
    {
        string LatestFileName = GetLastWrittenBatchFile();
        if (System.IO.File.Exists(BatchPath + LatestFileName))
        {
            System.Diagnostics.ProcessStartInfo procinfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
            procinfo.UseShellExecute = false;
            procinfo.RedirectStandardError = true;
            procinfo.RedirectStandardInput = true;
            procinfo.RedirectStandardOutput = true;

            System.Diagnostics.Process process = System.Diagnostics.Process.Start(procinfo); 
            System.IO.StreamReader stream = System.IO.File.OpenText(BatchPath + LatestFileName);
            System.IO.StreamReader sroutput = process.StandardOutput;
            System.IO.StreamWriter srinput = process.StandardInput;


            while (stream.Peek() != -1)
            {
                srinput.WriteLine(stream.ReadLine());
            }

            Log.Flow_writeToLogFile("Executed .Bat file : " + LatestFileName);

            process.WaitForExit(1000);

            if (process.ExitCode != 0)
            {
                int iExitCode = process.ExitCode;
            }
            stream.Close();
            process.Close();
            srinput.Close();
            sroutput.Close(); 
        }
        else
        {
            ExceptionHandler.writeToLogFile("File not found");
        }
    }
    catch (Exception ex)
    {
        ExceptionHandler.writeToLogFile(System.Environment.NewLine + "Target  :  " + ex.TargetSite.ToString() + System.Environment.NewLine + "Message :  " + ex.Message.ToString() + System.Environment.NewLine + "Stack   :  " + ex.StackTrace.ToString());
    }
} 

_________________ Update ___________________

script inside Batchfile: [Note that Notepads.exe is incorrect to get the error]

START Notepads.EXE

"if"% ERRORLEVEL% "==" 1 "exit / B 1"

+3
source share
5 answers

, , , , , script .

:

    /// <summary>
    /// Execute external process.
    /// Block until process has terminated.
    /// Capture output.
    /// </summary>
    /// <param name="binaryFilename"></param>
    /// <param name="arguments"></param>
    /// <param name="currentDirectory"></param>
    /// <param name="priorityClass">Priority of started process.</param>
    /// <returns>stdout output.</returns>
    public static string ExecuteProcess(string binaryFilename, string arguments, string currentDirectory, ProcessPriorityClass priorityClass)
    {
        if (String.IsNullOrEmpty(binaryFilename))
        {
            return "no command given.";
        }

        Process p = new Process();
        p.StartInfo.FileName = binaryFilename;
        p.StartInfo.Arguments = arguments;
        p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.UseShellExecute = false;
        if (!String.IsNullOrEmpty(currentDirectory))
            p.StartInfo.WorkingDirectory = currentDirectory;
        p.StartInfo.CreateNoWindow = false;

        p.Start();
        // Cannot set priority process is started.
        p.PriorityClass = priorityClass;

        // Must have the readToEnd BEFORE the WaitForExit(), to avoid a deadlock condition
        string output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();

        if (p.ExitCode != 0)
        {
            throw new Exception(String.Format("Process '{0} {1}' ExitCode was {2}",
                                 binaryFilename,
                                 arguments,
                                 p.ExitCode));   
        }
        //string standardError = p.StandardError.ReadToEnd();
        //if (!String.IsNullOrEmpty(standardError))
        //{
        //    throw new Exception(String.Format("Process '{0} {1}' StandardError was {2}",
        //                         binaryFilename,
        //                         arguments,
        //                         standardError));
        //}

        return output;
    }

​​ .

script , , script .

+5

Process.ExitCode , ? , , , .

, using, , - , IO. -, - , , .

+2

you can get it from procinfo.ExitCode

0
source
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(filename);
                    psi.RedirectStandardOutput = true;
                    psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    psi.UseShellExecute = false;
                    System.Diagnostics.Process listFiles;
                    listFiles = System.Diagnostics.Process.Start(psi);
                    System.IO.StreamReader myOutput = listFiles.StandardOutput;
                    listFiles.WaitForExit(2000);
                    if (listFiles.HasExited)
                    {
                        string output = myOutput.ReadToEnd();
                        MessageBox.Show(output);
                    }
0
source

Use ExitCode as shown below:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = @"usbformat.bat";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true; // change to false to show the cmd window
proc.Start();

proc.WaitForExit();

if (proc.ExitCode != 0)
   {
       return false;
   }
   else
   {
       return true;
   }
0
source

Source: https://habr.com/ru/post/1765227/


All Articles