Executing batch file with ProcessStartInfo

和自甴很熟 提交于 2020-01-05 04:58:10

问题


I am using ProcessStartInfo class to execute a batch file. But I am not so aware of using it properly. When I execute a batch file can we track is there any error or not. In my scenario, batch will start another process and it is successfully started it will be keep on executing. And if there is any error executing batch file it will exit. This is the code I am using.

I have to track both successfull start and failure as well.

internal bool ExecuteBatchFile(string fileName, int executionTime)
    {
        var exitCode = -1;
        var error = string.Empty;
        try
        {

            var hubStartInfo = new ProcessStartInfo
            {
                CreateNoWindow = false,
                FileName = fileName,
                UseShellExecute = false
            };

            var process = new Process { StartInfo = hubStartInfo };
            process.Start();
            process.WaitForExit(executionTime);

            if (process.HasExited)
            {
                exitCode = process.ExitCode;
                if (exitCode == 0)
                {
                    return true;
                }
                error = process.StandardError.ReadToEnd();
            }
            else
            {
                return true;
            }

            return false;
        }
        catch (Exception e)
        {
            return false;
        }
    }

Thanks


回答1:


See here for info on launching a process. Example 2 has info on monitoring the external process

private void simpleRun_Click(object sender, System.EventArgs e)
{
  System.Diagnostics.Process.Start(@"C:\listfiles.bat");
}


来源:https://stackoverflow.com/questions/11454644/executing-batch-file-with-processstartinfo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!