c# - 使用c#从CMD获取Exitcode

标签 c#

我正在使用以下代码将路径、可执行名称和参数写入批处理文件,并使用 C# 通过 CMD 执行它。问题是有时应用程序在执行批处理文件后启动。 C# 代码发送给我异常或任何通知。

为此,我想从 CMD 获取 Exitcode 以确定命令是否正确执行。 我如何确定退出代码?

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

________________更新_____________________

Batchfile里面的脚本:【注意Notepads.exe是错误的获取错误】

开始 记事本.EXE

“如果“%ERRORLEVEL%”==“1”退出/B 1”

最佳答案

直接运行流程比使用创建稍后执行的批处理文件要容易得多,因为您使用批处理脚本层会失去一些控制。

改用这段代码:

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

我在许多项目中使用它,它的效果非常好。

如果您必须使用批处理脚本路线,请确保批处理脚本正确设置退出代码。

关于c# - 使用c#从CMD获取Exitcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3732959/

相关文章:

c# - 将当前鼠标位置传递给 ViewModel?

c# - 为什么 int.Max+ int.Max = -2

c# - 我应该将我的 View 页面重新用于显示/添加/更新页面吗?

C# 结构体使用技巧?

c# - 控制台或图形游戏设计?

c# - 未从 Godaddy Hosted Exchange 收到 Exchange 2007 推送通知

c# - 支持按钮保持的 ASP.NET NumericUpDown Extender?

c# - 带有引用类型参数的 ref 关键字

c# - 通过反射动态继承内部类

c# - 在 Azure 存储上,CanGenerateSasUri 始终为 false