C# 使用c从CMD获取Exitcode#
我使用以下代码将路径、可执行文件名和参数写入批处理文件,并使用c#通过CMD执行它。问题是,有时应用程序dosent在执行批处理文件后启动。c代码没有给我例外或任何通知 我想从CMD获取Exitcode,以确定命令是否正确执行。 如何确定退出代码C# 使用c从CMD获取Exitcode#,c#,C#,我使用以下代码将路径、可执行文件名和参数写入批处理文件,并使用c#通过CMD执行它。问题是,有时应用程序dosent在执行批处理文件后启动。c代码没有给我例外或任何通知 我想从CMD获取Exitcode,以确定命令是否正确执行。 如何确定退出代码 public void Execute() { try { string LatestFileName = GetLastWrittenBatchFile(); if (System.IO.File.
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内的脚本:[请注意,notepad.exe获取错误信息是错误的]
开始
Notepads.EXE
“如果“%ERRORLEVEL%”==“1”退出/B 1”属性是否没有提供您想要的内容?显然,您需要确保批处理文件本身使用正确的退出代码退出,以镜像它正在运行的应用程序
顺便说一句,您应该使用
using
语句来确保在遇到异常时关闭所有相关流——我建议使用异步方式来响应来自应用程序的数据,而不是同步IO。如果您坚持使用同步IO,那么应该让另一个线程读取standard error-否则,如果进程将大量数据写入standard error,它将阻止等待您清除缓冲区。直接运行该过程比创建批处理文件(稍后执行)要容易得多,因为使用批处理脚本层会失去一些控制
请改用此代码:
/// <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;
}
//
///执行外部流程。
///阻止,直到进程终止。
///捕获输出。
///
///
///
///
///已启动进程的优先级。
///标准输出。
公共静态字符串ExecuteProcess(字符串二进制文件名、字符串参数、字符串currentDirectory、ProcessPriorityClass priorityClass)
{
if(String.IsNullOrEmpty(binaryFilename))
{
返回“未发出命令。”;
}
过程p=新过程();
p、 StartInfo.FileName=二进制文件名;
p、 StartInfo.Arguments=参数;
p、 StartInfo.WindowStyle=ProcessWindowStyle.Hidden;
p、 StartInfo.RedirectStandardOutput=true;
p、 StartInfo.RedirectStandardError=true;
p、 StartInfo.UseShellExecute=false;
如果(!String.IsNullOrEmpty(currentDirectory))
p、 StartInfo.WorkingDirectory=currentDirectory;
p、 StartInfo.CreateNoWindow=false;
p、 Start();
//无法设置进程启动时的优先级。
p、 PriorityClass=PriorityClass;
//必须在WaitForExit()之前具有readToEnd,以避免出现死锁情况
字符串输出=p.StandardOutput.ReadToEnd();
p、 WaitForExit();
如果(p.ExitCode!=0)
{
抛出新异常(String.Format(“进程{0}{1}”ExitCode为{2}”),
二进制文件名,
论据,
p、 退出代码);
}
//字符串standardError=p.standardError.ReadToEnd();
//如果(!String.IsNullOrEmpty(standardError))
//{
//抛出新异常(String.Format(“进程{0}{1}”StandardError为{2}”),
//二进制文件名,
//论据,,
//标准误差);
//}
返回输出;
}
我在许多项目中使用它,它就像一个魅力
如果必须执行批处理脚本路径,请确保批处理脚本正确设置了exitcode。您可以从
procinfo.exitcode
使用exitcode,如下所示:
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);
}
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;
}
@Andreas Paulsson,我需要按照我的要求使用batchfile。如何确保批处理脚本正确设置exitcode?@Anuya:在批处理脚本末尾添加一行,显示“如果“%ERRORLEVEL%”==“1”退出/B 1”。@Andreas Paulsson,请查看批处理文件中我的srcipt的更新。它没有给我任何通知。我做错什么了吗?@Anuya:删除外部双引号。至于创建字符串ic#,请使用字符串mystring=@“if”“%ERRORLEVEL%”==“1”“exit/b1”@安德烈亚斯·保尔森,是的,那是个错误,我现在改正了。但仍然没有得到任何错误。在执行批处理文件后,我必须从c#获取ErrorLevel吗?对我来说很好